﻿
function reloadBizPackForm() {
  var retData = yddser.getPackList();
  if (cm.dataNotOk(retData)) {
    return;
  }

  // var fakeData = {
  //   'createTime': new Date().getTime(),
  //   'id': 'fake000000001',
  //   'oid': 'fake000000001',
  //   'name': 'fake name',
  //   'text': 'fake text <span class="tree-num">(13)</span>'
  // }
  // fakeData = Object.assign({}, retData.data[0].children[0], fakeData);
  // retData.data[0].children.push(fakeData);

  $('.cube_dimension_tree').data('jstree', false).empty();
  $('.cube_dimension_tree').jstree({
    'core': {
      "check_callback": true,
      'data': retData.data,
    },
    "types": {
      "#": {"max_children": 1, "max_depth": 4, "valid_children": ["root"]},
      "root": {"icon": "../main/img/folder.png", "valid_children": ["default", "file"]},
      "default": {"valid_children": ["default", "file"]},
      "file": {"icon": "../main/img/file.png", "valid_children": []}
    },
    "plugins": ["dnd", "search", "state", "types", "wholerow"]
  })
}

var cfg={
  cfg_top:"../ser/",
  cfg_form :"../ser/form/",
  cfg_user :"../ser/user/",
  cfg_form_dgn:"../ser/form/design/",
  cfg_user_dgn :"../ser/user/design/",
  cfg_form_run: "../ser/form/run/",
  cfg_user_run:"../ser/user/run/",
  cfg_base_run:"../ser/base/",
  cfg_base_dgn:"../ser/base/"
};

var ns = typeof(GcSpread) != "undefined" ? GcSpread.Sheets:null;
function DatePickerCellType() {
}
if ( ns != null ){
  DatePickerCellType.prototype = ns != null ? new ns.CustomCellType() : null;

  DatePickerCellType.prototype.createEditorElement = function (context) {
    //Create input presenter.
    return document.createElement("input");
  };
  DatePickerCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
    //Initialize input editor.
    if (editorContext) {
      $editor = $(editorContext);
      ns.CustomCellType.prototype.activateEditor.apply(this, arguments);
      $editor.datepicker();
      $editor.css("position", "absolute");
      $editor.attr("gcUIElement", "gcEditingInput");
      $(".ui-datepicker").attr("gcUIElement", "gcEditingInput");
    }
  }
  DatePickerCellType.prototype.deactivateEditor = function (editorContext, context) {
    //Remove input editor when end editor status.
    if (editorContext) {
      var element = editorContext;
      $(element).datepicker("hide");
      $(element).datepicker("destroy");
    }
    ns.CustomCellType.prototype.deactivateEditor.apply(this, arguments)
  };
  DatePickerCellType.prototype.setEditorValue = function (editor, value, context) {
    //Sync value from Cell value to editor value.
    $(editor).datepicker("setDate", value);
  };
  DatePickerCellType.prototype.getEditorValue = function (editor, context) {
    //Sync value from editor value to cell value.
    return $(editor).datepicker("getDate");
  };
  DatePickerCellType.prototype.updateEditor = function (editorContext, cellStyle, cellRect, context) {
    if (editorContext) {
      $editor = $(editorContext);
      $editor.css("width", cellRect.width - 1);
      $editor.css("height", cellRect.height - 3);
    }
  };
}


(function($) {
  var privateFunction = function() {
    // 代码在这里运行
  }

  var methods = {
    init: function(options) {
      return this.each(function() {
        var $this = $(this);
        var settings = $this.data('departmentpicker');

        if(typeof(settings) == 'undefined') {

          var defaults = {
            propertyName: 'value',
            entry: [{name: '请选择', value: ''}],
            isShowing: false,
            onSelect: function() {
              $this.val(this.value);
              $('#ui-departmentpicker-div').hide();
              $(document).unbind('mousedown.departmentpicker');
            },
            onSomeEvent: function() {}
          }

          settings = $.extend({}, defaults, options);

          $this.data('departmentpicker', settings);
        } else {
          settings = $.extend({}, settings, options);
        }

        // 代码在这里运行
        if($('#ui-departmentpicker-div').length == 0) {
          var dpt = document.createElement('div');
          $(dpt).attr('id', 'ui-departmentpicker-div');
          $(dpt).addClass('ui-departmentpicker');
          $(dpt).append('<select></select>');
          $(dpt).appendTo('body');
        }


        $this.bind('focus', function() {
          settings.isShowing = true;
          $select = $('#ui-departmentpicker-div select');
          $select.empty();
          for(var i = 0; i < settings.entry.length; i++) {
            $select.append('<option value="' + settings.entry[i].value + '">' + settings.entry[i].name + '</option>');
          }
          var top = $this.offset().top + $this.outerHeight();
          var left = $this.offset().left;
          $('#ui-departmentpicker-div').css({'position': 'absolute', 'top': top + 'px', 'left': left + 'px'}).show();
          if($this.val() != null && $this.val() != '') {
            $select.val($this.val());
          }
          $select.unbind('change');
          $select.bind('change', settings.onSelect);
          $(document).bind('mousedown.departmentpicker', function() {
            var el = event.target;
            var cal = $('#ui-departmentpicker-div')[0];

            while (true) {
              if (el == cal || el == $this.get(0)) {
                break;
              } else if (el == document) {
                settings.isShowing = false;
                $('#ui-departmentpicker-div').hide();
                $(document).unbind('mousedown.departmentpicker');
                break;
              } else {
                el = $(el).parent()[0];
              }
            }
          })
        })

      });
    },
    hide: function(options) {
      return $(this).each(function() {
        var $this = $(this);

        var settings = $this.data('departmentpicker');
        if(settings.isShowing) {
          $('#ui-departmentpicker-div').hide();
          $(document).unbind('mousedown.departmentpicker');
        }
      })
    },
    destroy: function(options) {
      return $(this).each(function() {
        var $this = $(this);

        $this.removeData('departmentpicker');
      });
    },
    val: function(options) {
      var someValue = this.eq(0).html();

      return someValue;
    },
    getDepartment: function(options) {
      return $(this).val();
    },
    setDepartment: function(options) {
      return $(this).each(function() {
        var $this = $(this);

        $this.val(options);
      });
    }
  };

  $.fn.departmentpicker = function() {
    var method = arguments[0];

    if(methods[method]) {
      method = methods[method];
      arguments = Array.prototype.slice.call(arguments, 1);
    } else if( typeof(method) == 'object' || !method ) {
      method = methods.init;
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.departmentpicker' );
      return this;
    }

    return method.apply(this, arguments);

  }

})(jQuery);

function DepartmentPickerCellType() {
}
if ( ns != null ){
  DepartmentPickerCellType.prototype = new ns.CustomCellType();

  DepartmentPickerCellType.prototype.createEditorElement = function (context) {
    //Create input presenter.
    return document.createElement("input");
  };
  DepartmentPickerCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
    //Initialize input editor.
    if (editorContext) {
      $editor = $(editorContext);
      ns.CustomCellType.prototype.activateEditor.apply(this, arguments);

      $editor.css("position", "absolute");
      $editor.departmentpicker({entry: [{name: 'Developer', value: 'Developer'}, {name: 'HR', value: 'HR'},
        {name: 'Marketing', value: 'Marketing'}, {name: 'Sales', value: 'Sales'}]});
      $editor.attr("gcUIElement", "gcEditingInput");
      $(".ui-departmentpicker").attr("gcUIElement", "gcEditingInput");
    }
  }
  DepartmentPickerCellType.prototype.deactivateEditor = function (editorContext, context) {
    //Remove input editor when end editor status.
    if (editorContext) {
      var element = editorContext;
      $(element).departmentpicker("hide");
      $(element).departmentpicker("destroy");
    }
    ns.CustomCellType.prototype.deactivateEditor.apply(this, arguments)
  };
  DepartmentPickerCellType.prototype.setEditorValue = function (editor, value, context) {
    //Sync value from Cell value to editor value.
    $(editor).departmentpicker("setDepartment", value);
  };
  DepartmentPickerCellType.prototype.getEditorValue = function (editor, context) {
    //Sync value from editor value to cell value.
    return $(editor).departmentpicker("getDepartment");
  };
  DepartmentPickerCellType.prototype.updateEditor = function (editorContext, cellStyle, cellRect, context) {
    if (editorContext) {
      $editor = $(editorContext);
      $editor.css("width", cellRect.width - 1);
      $editor.css("height", cellRect.height - 3);
    }
  };
}

function JsTreeCellType(data) {
  this.data = data ? data : [
    { "id" : "ajson1", "parent" : "#", "text" : "Simple root node" },
    { "id" : "ajson2", "parent" : "#", "text" : "Root node 2" },
    { "id" : "ajson3", "parent" : "ajson2", "text" : "Child 1" },
    { "id" : "ajson4", "parent" : "ajson2", "text" : "Child 2" },
    { "id" : "ajson5", "parent" : "ajson2", "text" : "Child 3" },
    { "id" : "ajson6", "parent" : "ajson2", "text" : "Child 4" },
  ];
}

if ( ns != null ) {
  JsTreeCellType.prototype = new ns.CustomCellType();
  JsTreeCellType.prototype.createEditorElement = function (context) {
    //Create input presenter.
    var div = document.createElement("div");
    var $div = $(div);
    $div.attr("gcUIElement", "gcEditingInput");
    $div.addClass('jstree-cell')
    $div.append('<input type="text" /><div class="jstree-wrapper"></div>');

    return div;
  };
  JsTreeCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
    //Initialize input editor.
    if (editorContext) {
      $editor = $(editorContext);
      ns.CustomCellType.prototype.activateEditor.apply(this, arguments);
      var self = this;
      $editor.find('.jstree-wrapper').jstree({ 'core' : {
        'data' : self.data
      } });
      setTimeout(function() {
        $editor.find('input').focus()
      },0)
    }
  }
  JsTreeCellType.prototype.deactivateEditor = function (editorContext, context) {
    //Remove input editor when end editor status.
    if (editorContext) {
      var element = editorContext;
    }
    ns.CustomCellType.prototype.deactivateEditor.apply(this, arguments)
  };
  JsTreeCellType.prototype.setEditorValue = function (editor, value, context) {
    //Sync value from Cell value to editor value.
    $editor = $(editor);
    var $input = $editor.find('input');
    $input.val(value);
    setTimeout(function() {
      var ref = $editor.find('.jstree-wrapper').jstree(true);
      ref.select_node(value);
    }, 100)
  };
  JsTreeCellType.prototype.getEditorValue = function (editor, context) {
    //Sync value from editor value to cell value.
    var ref = $editor.find('.jstree-wrapper').jstree(true);
    var sel = ref.get_selected();
    if(!sel.length) {
      return 'jstree';
    }
    return sel;
  };
  JsTreeCellType.prototype.updateEditor = function (editorContext, cellStyle, cellRect, context) {
    if (editorContext) {
      $editor = $(editorContext);
      $editor.css("width", cellRect.width - 1);
      $editor.css("height", cellRect.height - 3);
    }
  };

}

function ListCellType(data) {
  this.data = data ? data : ['a', 'b', 'c', 'd'];
}

if ( ns != null ){
  ListCellType.prototype = new ns.CustomCellType();
  ListCellType.prototype.createEditorElement = function (context) {
    //Create input presenter.
    var div = document.createElement("div");
    var $div = $(div);
    $div.attr("gcUIElement", "gcEditingInput");
    $div.css('position', 'absolute');
    $div.append($('#template').html());

    return div;
  };
  ListCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
    //Initialize input editor.
    if (editorContext) {
      $editor = $(editorContext);
      ns.CustomCellType.prototype.activateEditor.apply(this, arguments);
      setTimeout(function() {
        var vueIns = new Vue({
          el: '.vue-wrapper',
          data: {
            cellValue: [],
            items: []
          },
          methods: {
            save: function() {
              console.log('save: ' + this.cellValue);
            },
            cancel: function() {
              console.log('cancel: ' + this.cellValue);
            }
          }
        });

        $editor.data('vueIns', vueIns);
        $editor.find('input').focus()
      }, 0)
    }
  };
  ListCellType.prototype.deactivateEditor = function (editorContext, context) {
    //Remove input editor when end editor status.
    if (editorContext) {
      var element = editorContext;
    }
    ns.CustomCellType.prototype.deactivateEditor.apply(this, arguments)
  };
  ListCellType.prototype.setEditorValue = function (editor, value, context) {
    //Sync value from Cell value to editor value.
    $editor = $(editor);
    setTimeout(function() {
      var vueIns = $editor.data('vueIns');
      if(vueIns) {
        vueIns.$data.cellValue = value;
        var items = value.split(',');
        vueIns.$data.items = items;
      }
    }, 0)
  };
  ListCellType.prototype.getEditorValue = function (editor, context) {
    //Sync value from editor value to cell value.
    return $(editor).find('input').val();
  };
  ListCellType.prototype.updateEditor = function (editorContext, cellStyle, cellRect, context) {
    if (editorContext) {
      $editor = $(editorContext);
      $editor.css("width", cellRect.width - 1);
      $editor.css("height", cellRect.height - 3);
    }
  };

}


var yddser = {
  createObj:function (idType, withCmInput) {
    var ret = yddser.getNewId(idType);
    if (cm.dataNotOk(ret)) {
      cn.showFailedDlg(ret.msg);
      return;
    }

    var data;
    if ( idType =="bsd" ){
      data = {oid:cm.dataVal(ret),groupName:"", dataShowType:1,itemId:"",itemText:"",ext1:"",ext2:"",ext3:""};
    }
    else if (idType =="cd"){
      data = {oid:cm.dataVal(ret),codeName:"",description:"",codePrefix:"demo",codeDataFmt:"YY",codeDecimals:2,
        codeStart:1,codeStep:1,cur:0,codeGen:1};
    }
    if( withCmInput ){
      yddser.makeDataInputVal(idType, data);
    }
    return data;
  },
  makeDataInputVal:function (idType,data,func) {
    cm.delKey(data,"vm_arr");
    if (idType == "bsd"){
      cm.forEachKeys(data, function (obj,key) {
        var text = "";
        var editType = 1;
        if ( key =="groupName" ){
          text = "数据显示名称:";
        }
        else if (key =="dataShowType" ){
          editType =2;
          text = "显示样式:";
        }
        else if (key =="id" ){
          text = "数据条目值:";
        }
        else if (key =="text" ){
          text = "数据条目显示名称:";
        }
        else if (key =="ext1" ){
          text = "扩展1:";
        }
        else if (key =="ext2" ){
          text = "扩展2:";
        }
        else if (key =="ext3" ){
          text = "扩展3:";
        }
        var ret = {};
        if ( func ){
          ret = func(idType,key,text,obj);
        }
        if ( text ){
          cm.makeCmInputObj(data,key, text, editType, ret.disable);
        }
      });
    }
  },
  addOrUpdateDept: function (obj) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "addOrUpdateDept", "jsonObj=" + cm.str(obj)));
  },
  addOrUpdateUser: function (obj) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "addOrUpdateUser", "jsonObj=" + cm.str(obj)));
  },
  getSerData: function (account) {
    return cn.getRetData(cm.ajax(cfg.cfg_user + "getUser", "account=" + account));
  },
  addOrUpdatePack: function (obj) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_dgn + "addOrUpdatePack", "jsonObj=" + cm.str(obj)));
  },
  getPackList: function () {
    var ret = cn.getRetData(cm.ajax(cfg.cfg_top + "getPackList", ""));
    if (cm.dataNotOk(ret)) {
      return ret;
    }

    cm.setTreeEachItem(ret.data, "children", function (obj) {
      obj.id = obj.oid;
      obj.text = obj.name;
      if (cm.strStartWith(obj.id, 'pk')) {
        obj.type = 'root';
      } else {
        obj.type = 'file';
      }
    });
    return ret;
  },
  getPackList2: function () {
    var ret = yddser.getPackList();
    if (cm.dataNotOk(ret)) {
      return {};
    }
    return ret;
  },
  addOrUpdateForm: function (obj) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_dgn + "addOrUpdateForm", "jsonObj=" + cm.str(obj)));
  },
  addOrUpdateFormTmpl: function (obj) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_dgn + "addOrUpdateFormTmpl", "jsonObj=" + cm.str(obj)));
  },
  saveFormStyle: function (formId, styleData) {
    return cn.getRetData(cm.ajaxJBody(cfg.cfg_form_dgn + "saveFormStyle", cm.str({
      formId: formId,
      styleData: styleData
    })));
  },
  getForm: function (formId) {
    return cn.getRetData(cm.ajax(cfg.cfg_form + "getForm", "formId=" + formId));
  },
  getFormTmpl: function (tmplId) {
    return cn.getRetData(cm.ajax(cfg.cfg_form + "getFormTmpl", "tmplId=" + tmplId));
  },
  createTable: function (cp, tableArr) {
    var reqMD = new ReqMDTable();
    reqMD.tableArr = tableArr;
    reqMD.packId = cp.formObj.packId;
    reqMD.formId = cp.formObj.oid;
    reqMD.extstyledata = cp.saveToJsonStr();
    return cn.getRetData(cm.ajaxJBody(cfg.cfg_form_dgn + "createTable", cm.str({jsonObj: cm.str(reqMD)})));
  },
  addOrUpdateFormData: function (cp, pname, asNew) {
    var data;
    var reqData = cn.getReqMDData(cp, cp.formObj.packId, cp.formObj.oid, 0, cp.currentSheet2().customVar(), cp.formObj.tableArr, asNew);
    var retD = cn.getRetData(cm.ajax(cfg.cfg_form_run + "addOrUpdateFormData", "jsonObj=" + cm.str(reqData) +"&asNew="+asNew));
    retD.exCode = reqData.dataStatus;
    if (cm.dataOk(data)) {
      if (cp.tmpData != null && cp.tmpData.deletedDids != null) {
        cp.tmpData.deletedDids = {};
      }
    }
    return retD;
  },
  addOrUpdateFormTmplData: function (cp, pname) {
    var data;
    var reqData = cn.getReqMDData(cp, cp.formObj.packId, cp.formObj.oid, 0, cp.currentSheet2().customVar(), cp.formObj.tableArr);
    var retD = cn.getRetData(cm.ajax(cfg.cfg_form_dgn + "addOrUpdateFormTmplData", "jsonObj=" + cm.str(reqData)));
    retD.exCode = reqData.dataStatus;
    if (cm.dataOk(data)) {
      if (cp.tmpData != null && cp.tmpData.deletedDids != null) {
        cp.tmpData.deletedDids = {};
      }
    }
    return retD;
  },
  getFormData: function (dataIndex, genTree) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_run + "getFormData", "dataIndex=" + dataIndex));
  },
  findDataByDate: function (formId, dateNum) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_run + "findDataByDate", "formId=" + formId + "&dateNum=" + dateNum));
  },
  getFormFindArr: function (formId) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_run + "getFormFindArr", "formId=" + formId));
  },
  getFormTmplList:function(formId, withImage,pageNum,perPageNum){
    return cn.getRetData(cm.ajax(cfg.cfg_form + "getFormTmplList", "formId=" + formId +"&withImage=" + (withImage?"1":"0")+"&pageNum=" + pageNum + "&perPageNum=" + perPageNum));
  },
  getFormTmplImage:function(tmplId){
    return cn.getRetData(cm.ajax(cfg.cfg_form + "getFormTmplImage", "tmplId=" + tmplId));
  },
  findDataByFindArr: function (formId, jsonObj, pageNum, perPageNum) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_run + "findDataByFindArr", "formId=" + formId + "&jsonObj=" + cm.str(jsonObj)
      + "&pageNum=" + pageNum+ "&perPageNum=" + perPageNum));
  },
  changePwd: function (userId, oldPwd, pwd) {
    return cn.getRetData(cm.ajax(cfg.cfg_user + "changePwd", "oldPwd=" + oldPwd + "&pwd=" + pwd));
  },
  getDept: function (deptId, genTree) {
    var ret = cn.getRetData(cm.ajax(cfg.cfg_user + "getDept", "deptId=" + deptId));
    if (genTree && cm.dataOk(ret)) {
      cm.setTreeEachItem(ret.data, "children", function (obj) {
        obj.id = obj.oid;
        obj.text = obj.deptName;
        obj.type = 'department';
      });
    }
    return ret;
  },
  getDeptSubCode: function (deptCode) {
    return cn.getRetData(cm.ajax(cfg.cfg_user + "getDeptSubCode", "deptCode=" + deptCode));
  },
  delDept: function (deptId) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "delDept", "deptId=" + deptId));
  },
  delSubTableData: function (tableId, did) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_run + "delSubTableData", "tableId=" + tableId + "&did=" + did));
  },
  delForm: function (formId) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_dgn + "delForm", "formId=" + formId));
  },
  delPack: function (packId) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_dgn + "delPack", "packId=" + packId));
  },
  getDeptUser: function (deptId, genTree) {
    var ret = cn.getRetData(cm.ajax(cfg.cfg_user + "getDeptUser", "deptId=" + deptId));
    if (genTree && cm.dataOk(ret)) {
      cm.setTreeEachItem(ret.data, "children", function (obj) {
        obj.id = obj.oid;
        obj.text = obj.userName;
        obj.type = 'department';
      });
    }
    return ret;
  },
  getUser: function (userId) {
    return cn.getRetData(cm.ajax(cfg.cfg_user + "getUser", "userId=" + userId));
  },
  getUser2: function (userId, userType, withDept) {
    return cn.getRetData(cm.ajax(cfg.cfg_user + "getUser2", "userId=" + userId + "&userType=" + userType + "&withDept=" + withDept));
  },
  logout:function () {
    return cn.getRetData(cm.ajax(cfg.cfg_top + "logout",""));
  },
  getCurUser: function () {
    return cn.getRetData(cm.ajax(cfg.cfg_user + "getCurUser", ""));
  },
  delUser: function (userId) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "delUser", "userId=" + userId));
  },
  addOrUpdateRight: function (obj) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "addOrUpdateRight", "jsonObj=" + cm.str(obj)));
  },
  delRightToUserForm: function (deptUserId, packFormId) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "delRightToUserForm", "deptUserId=" + deptUserId + "&packFormId=" + packFormId));
  },
  getRight: function (rightId, genTree) {
    var retData = cn.getRetData(cm.ajax(cfg.cfg_user + "getRight", "rightId=" + rightId));
    if (genTree && cm.dataOk(retData)) {
      cm.setTreeEachItem(retData.data, "children", function (obj) {
        obj.id = obj.oid;
        obj.text = obj.name;
        obj.type = 'department';
      });
    }
    return retData;
  },
  getRightPackFormSetting: function (deptUserId) {
    return cn.getRetData(cm.ajax(cfg.cfg_user + "getRightPackFormSetting", "deptUserId=" + deptUserId));
  },
  getRightAllByUserForm: function (deptUserId, packFormId) {
    return cn.getRetData(cm.ajax(cfg.cfg_top + "getRightAllByUserForm", "deptUserId=" + deptUserId + "&packFormId=" + packFormId));
  },
  getRightByUserForm: function (deptUserId, packFormId) {
    return cn.getRetData(cm.ajax(cfg.cfg_top + "getRightByUserForm", "deptUserId=" + deptUserId + "&packFormId=" + packFormId));
  },
  addRightToUserForm: function (deptUserId, packFormId, rightId) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "addRightToUserForm", "deptUserId=" + deptUserId + "&packFormId=" + packFormId + "&rightId=" + rightId));
  },
  resetRightByUserForm: function (jsonObj) {
    return cn.getRetData(cm.ajax(cfg.cfg_user_dgn + "resetRightByUserForm", "jsonObj=" + cm.str(jsonObj)));
  },
  getNewId: function (idType) {
    return cn.getRetData(cm.ajax(cfg.cfg_top + 'getNewId', "idType=" + idType));
  },
  getDemoCode: function (jsonObj) {
    return cm.ajax(cfg.cfg_base_run + 'getDemoCode', "jsonObj=" + cm.str(jsonObj));
  },
  addOrUpdateCode: function (jsonObj) {
    return cn.getRetData(cm.ajax(cfg.cfg_base_run + "addOrUpdateCode", "jsonObj=" + cm.str(jsonObj)));
  },
  getCode: function (codeId) {
    return cn.getRetData(cm.ajax(cfg.cfg_base_run + "getCode", "codeId=" + codeId));
  },
  deleteCode: function (codeId) {
    return cn.getRetData(cm.ajax(cfg.cfg_base_run + "deleteCode", "codeId=" + codeId));
  },
  getNextCode: function (codeId) {
    return cn.getRetData(cm.ajax(cfg.cfg_base_run + "getNextCode", "codeId=" + codeId));
  },
  deleteDataset: function (codeId) {
    return cn.getRetData(cm.ajax(cfg.cfg_form_dgn + "deleteDataset", "formId=" + codeId));
  },
  addOrUpdBaseDataItem: function (jsonObj) {
    return cn.getRetData(cm.ajax(cfg.cfg_base_run + "addOrUpdBaseDataItem", "jsonObj=" + cm.str(jsonObj)));
  },
  getGroupBaseData: function (groupName, showType, genTree) {
    var retData = cn.getRetData(cm.ajax(cfg.cfg_base_run + "getGroupBaseData", "groupName=" + groupName
      +"&dataShowType="+showType+"&genTree="+genTree));
    if (cm.dataOk(retData)) {
      cm.setTreeEachItem(retData.data, "children", function (obj) {
        obj.type = 'root';
        obj.id=obj.oid;
        obj.text=obj.itemText;
      });
    }
    return retData;
  },
  getGroupBaseDataOfParent: function (groupName, showType, parentId, genTree) {
    var retData = cn.getRetData(cm.ajax(cfg.cfg_base_run + "getGroupBaseDataOfParent", "groupName=" + groupName
      +"&dataShowType="+showType+"&genTree="+genTree+"&parentId="+parentId));
    if (cm.dataOk(retData)) {
      cm.setTreeEachItem(retData.data, "children", function (obj) {
        obj.type = 'root';
        obj.id=obj.oid;
        obj.text=obj.itemText;
      });
    }
    return retData;
  },
  getBaseDataItem: function (baseId) {
    return cn.getRetData(cm.ajax(cfg.cfg_base_run + "getBaseDataItem", "baseId=" + baseId));
  },
  deleteBaseDataItem: function (baseId) {
    return cn.getRetData(cm.ajax(cfg.cfg_base_run + "deleteBaseDataItem", "baseId=" + baseId));
  },
  deleteGroupBaseData: function (groupName) {
    var retData = cn.getRetData(cm.ajax(cfg.cfg_base_run + "deleteGroupBaseData", "groupName=" + groupName));
    return retData;
  },
  getAllGroupBaseData:function () {
    var retData =  cn.getRetData(cm.ajax(cfg.cfg_base_run + "getAllGroupBaseData"));
    if ( cm.dataOk(retData)) {
      cm.setTreeEachItem(retData.data, "children", function (obj) {
        obj.type = 'root';
        obj.id = obj.oid;
        obj.text = obj.groupName;
      });
    }
    return retData;
  }
};
/////////////////////

var Mg_AlignHType = {
  "MgAlignH_Default": 0,
  "MgAlignH_Left": 1,
  "MgAlignH_Right": 2,
  "MgAlignH_Center": 4,
  "MgAlignH_TextUniform": 64
};
var Mg_AlignVType = {
  "MgAlignV_Default": 0,
  "MgAlignV_Top": 8,
  "MgAlignV_Center": 32,
  "MgAlignV_Bottom": 16,
  "MgAlignV_TextUniform": 128
};

function icprange() {
  this.c1 = -1;
  this.r1 = -1;
  this.c2 = -1;
  this.r2 = -1;
  this.sheet = -1;
  this.abs = 0;
  this.iscell = false;
  this.varName = "";
}
icprange.prototype = {
  setRg: function (r1, c1, r2, c2, sheet, abs) {
    this.r1 = r1;
    this.c1 = c1;
    this.r2 = r2;
    this.c2 = c2;
    this.abs = abs;
    this.sheet = sheet;
    return this;
  },
  setAbs: function (pos, setv) {
    if (setv) {
      this.abs = this.abs | pos;
    }
    else {
      this.abs &= ~pos;
    }
    return this;
  },
  getAbs: function (pos) {
    return  this.abs & pos == pos;
  },
  setToEnd: function () {
    this.c2 = this.c1;
    this.r2 = this.r1;
    this.abs *= 4;
    return this;
  },
  absR: function () {
    return this.getAbs(1);
  },
  absC: function () {
    return this.getAbs(2);
  },
  absR2: function () {
    return this.getAbs(4);
  },
  absC2: function () {
    return this.getAbs(8);
  },
  offsetMulti: function (count, direction) {
    switch (direction) {
      case 1: {
        var num = this.colCount() * count;
        this.c2 = this.c1 - 1;
        this.c1 = this.c2 - num + 1;
      }
        break;
      case 2: {
        var num = this.rowCount() * count;
        this.r2 = this.r1 - 1;
        this.r1 = this.r2 - num + 1;
      }
        break;
      case 3: {
        var num = this.colCount() * count;
        this.c1 = this.c2 + 1;
        this.c2 = this.c1 + num - 1;
      }
        break;
      case 4: {
        var num = this.rowCount() * count;
        this.r1 = this.r2 + 1;
        this.r2 = this.r1 + num - 1;
      }
        break;

    }
  },
  mergeIcp: function (icp) {
    if (this.isEmpty()) {
      this.initBy(icp);
      return;
    }
    if (this.c1 > icp.c1)
      this.c1 = icp.c1;
    if (this.r1 > icp.r1)
      this.r1 = icp.r1;
    if (this.r2 < icp.r2)
      this.r2 = icp.r2;
    if (this.c2 < icp.c2)
      this.c2 = icp.c2;
    this.sheet = icp.sheet;
  },
  rowCount: function () {
    return this.r2 - this.r1 + 1;
  },
  colCount: function () {
    return this.c2 - this.c1 + 1;
  },
  mergeIcpArr: function (arr) {
    for (var i = 0; i < arr.length; i++) {
      this.mergeIcp(arr[i]);
    }
  },
  offsetBlock: function (rcount, ccount) {
    if (ccount != 0) {
      var colC = this.colCount();
      this.c1 += colC * ccount;
      this.c2 += colC * ccount;
    }
    if (rcount != 0) {
      var rowC = this.rowCount();
      this.r1 += rowC * rcount;
      this.r2 += rowC * rcount;
    }
  },
  genOffsetRg: function (offIcp, outIcp) {
    outIcp.varName = offIcp.varName;
    outIcp.c1 = this.c1 - offIcp.c1;
    outIcp.r1 = this.r1 - offIcp.r1;
    outIcp.r2 = this.r2 - offIcp.r2;
    outIcp.c2 = this.c2 - offIcp.c2;
    outIcp.sheet = this.sheet;
    return outIcp;
  },
  isEmpty: function () {
    return this.c1 == -1 && this.r1 == -1;
  },
  initBy: function (icp) {
    this.c1 = icp.c1;
    this.r1 = icp.r2;
    this.r2 = icp.r2;
    this.c2 = icp.c2;
    this.sheet = icp.sheet;
    this.abs = icp.abs;
  }

}

function ReqMDTable() {
  this.packId;
  this.formId;
  this.extstyledata;
}

//public static final int Type_None = -1;
//public static final int Type_int = 0;
//public static final int Type_long = 1;
//public static final int Type_dbl = 2;
//public static final int Type_String = 3;
//public static final int Type_Datetime = 4;  

var cm = {
  arrDelByArr:function (sArr, dArr, func,delType) {
    for (var v = sArr.length-1; v>=0; v-- ){
      for ( var t = dArr.length-1; t>=0; t--){
        var funret = func ? func(sArr[v],dArr[t]):0;
        if (funret==1){

        }
        else if ( funret==2){
          return;
        }
        else if (funret==0){
          if (delType==null || delType ==1 ){
            dArr.splice(t,1);
          }
          sArr.splice(v,1);
        }
      }
    }
  },
  myAlert: function (msg) {
    $('#my-alert .am-modal-bd').text(msg);
    $('#my-alert').modal();
  },
  encode:function (str) {
    return encodeURIComponent(str);
  },
  myAlertFunc: function (msg, inData, func) {
    $('#my-alert2 .am-modal-bd').text(msg);
    $('#my-alert2').data('inData', inData);
    $('#my-alert2').modal({
      relatedTarget: func,
      closeOnConfirm: true,
      onConfirm: function (e) {
        func($('#my-alert2').data('inData'));
      }
    });
  },
  loadingDlg:function (open, msg, func) {

    // if ( open ){
    //   $('#my-modal-loading').modal();
    // }
    // if ( !open ){
    //   $('#my-modal-loading').modal('close');
    // }
    // setTimeout(function() {
    //   $('#my-modal-loading').modal('close');
    // }, 100);
  },
  inputDlg:function (func) {
    $('#my-input').modal({
      relatedTarget: func,
      onConfirm: function (e) {
        func( e.data );
      },
      onCancel: function (e) {
      }
    });
  },
  makeCmInputObj:function (obj,key,text,editType,disable) {
    if(obj["vm_arr"] == null){
      obj["vm_arr"]=[];
    }
    var vmData = {vm_key:key,vm_val:obj[key], vm_text:text, vm_editType:editType};
    if(disable) {
      vmData.vm_disable=1;
    }
    obj["vm_arr"].push(vmData);
  },
  clearCmInputObj:function (obj) {
    cm.forEach(obj['vm_arr'],function (item) {
      obj[item['vm_key']]=item['vm_val'];
    });
    cm.delKey(obj,"vm_arr");
  },
  isEmptyArr:function(data) {
    return data == null || data.length == 0;
  },
  isBitOk: function (val, bit) {
    return ((val & (0x1 << bit)) >> bit) == 1;
  },
  setBit: function (val, val) {
    return val | (0x1 << bit)
  },
  clearBit: function (val, bit) {
    var a = 255;
    for (var i = 0; i <= bit; i++) {
      a = a << 1;
      if (i > 0) a++;
    }
    return val & a;
  },
  forEach: function (e, func) {
    if (e instanceof Array) {
      for (var i in e) {
        if (func != null) {
          func(e[i]);
        }
      }
    }
  },
  forEachKeys: function (obj, func) {
    Object.keys(obj).forEach(function (key) {
      if (func) {
        func(obj,key);
      }
    });
  },
  delKey:function (obj,key) {
    delete obj[key];
  },
  setTreeEachItem: function (treeObj, childrenNode, func) {
    if (treeObj == null) {
      return;
    }
    if (treeObj instanceof Array) {
      for (var i = 0; treeObj != null && i < treeObj.length; i++) {
        cm.setTreeEachItem(treeObj[i], childrenNode, func);
      }
    } else {
      if (func) {
        func(treeObj);
      }
      if (treeObj[childrenNode] != null && treeObj[childrenNode].length > 0) {
        for (var i = 0; i < treeObj.children.length; i++) {
          cm.setTreeEachItem(treeObj[childrenNode][i], childrenNode, func);
        }
      }
    }
  },
  RefStrToColRow: function (S, oicp) {
    S = S.toLowerCase();
    var i, j, icp;
    if (oicp == null) {
      icp = new icprange();
    }
    else
      icp = oicp;
    icp.setAbs(3, false);
    if (S.length < 1)
      return null;
    i = 0;
    if (S.charAt(i) == '$') {
      i++;
      icp.setAbs(1, true);
    }

    // 格式非法 $, 1, a, $a, $1 等样式 2个字符
    if (i >= S.length || !(S.charAt(i) >= 'a' && S.charAt(i) <= 'z'))
      return null;
    i++;
    if (i >= S.length)
      return null;
    var asi = 'a'.charCodeAt();
    // 3个字符, 实现 AAA23 3个字母的列头
    if ((S.charAt(i) >= 'a') && (S.charAt(i) <= 'z')) {
      if (S.charAt(i + 1) >= 'a' || S.charAt(i + 1) <= 'z') {
        icp.c1 = ((S.charAt(i - 1).charCodeAt() - asi + 1) * 26 * 26) + ((S.charAt(i).charCodeAt() - asi + 1) * 26) + (S.charAt(i + 1).charCodeAt() - asi + 1);
        i += 2;
      } else {
        icp.c1 = (S.charAt(i - 1).charCodeAt() - asi + 1) * 26 + S.charAt(i) - asi + 1;
        i++;
      }

    } else
      icp.c1 = S.charAt(i - 1).charCodeAt() - asi + 1;

    if (S.charAt(i) == '$') {
      i++;
      icp.setAbs(2, true);
    }
    for (j = i; j < S.length; j++) {
      if (!((S.charAt(j) >= '0') && (S.charAt(j) <= '9')))
        return icp;
    }

    var str = S.substring(i);
    icp.r1 = parseInt(str);
    return icp;
  },
  RefStrToRange: function (S, bSetEndWhenCellStr, sheet) {
    var i = S.indexOf(':');
    var ret;
    if (i < 0) {
      ret = cm.RefStrToColRow(S);
      if (ret != null && bSetEndWhenCellStr) {
        ret.r2 = ret.r1;
        ret.c2 = ret.c1;
      }
    } else {
      var end = S.substring(i + 1);
      var begin = S.substring(0, i);
      var ret = cm.RefStrToColRow(end);
      if (ret != null) {
        ret.setToEnd();
        ret = cm.RefStrToColRow(begin, ret);
      }

    }
    if (sheet != null)
      ret.sheet = sheet;
    return ret;
  },
  RgColRowToRefStr: function (r, c, r2, c2, sr, sc, sr2, sc2) {
    var data = cm.ColRowToRefStr(r, c, sr, sc);
    data += ":";
    data += cm.ColRowToRefStr(r2, c2, sr2, sc2);
    return data;
  },
  ColRowToRefStr: function (r, c, sr, sc) {
    var Result = "", str = "";
    c--;

    if (c < 26)
      Result = String.fromCharCode('A'.charCodeAt() + c);
    else if (c >= 26 && c < 26 * 26)
      Result = String.fromCharCode('@'.charCodeAt() + c / 26) + String.fromCharCode('A'.charCodeAt() + c % 26);
    else if (c >= 26 * 26)
      Result = String.fromCharCode('@'.charCodeAt() + c / 26 / 26) + String.fromCharCode('@'.charCodeAt() + c / 26) + String.fromCharCode('A'.charCodeAt() + c % 26);
    if (sc)
      Result = "$" + Result;

    if (sr)
      str = "$" + r;
    else
      str = "" + r;
    Result = Result + str;
    return Result;
  },
  strStartWith: function (ori, str) {
    var reg = new RegExp("^" + str);
    return reg.test(ori);
  },
  strEndWith: function (ori, str) {
    var reg = new RegExp(str + "$");
    return reg.test(ori);
  },
  str: function str(o) {
    return JSON.stringify(o);
  },
  strIsEmpty: function (o) {
    return o == null || o.length == 0;
  },
  strIsNotEmpty: function (o) {
    return !cm.strIsEmpty(o);
  },
  strSplit: function (str, s) {
    return str.split(s);
  },
  strSplitIdx: function (str, s, idx) {
    return str.split(s)[idx];
  },
  strToInt: function (s) {
    return Number(s);s
  },
  sleep:function(n){
    var start=new Date().getTime();
    while(true) if(new Date().getTime()-start>n) break;
  },
  obj: function obj(str) {
    return JSON.parse(str);
  },
  strFindSubfix: function (str, subfix) {
    var i = str.lastIndexOf(subfix)
    if (str.length - i == subfix.length) {
      return 1;
    }
    return -1;
  },
  cloneObj: function (obj) {
    var objClone;
    if (obj.constructor == Object) objClone = new obj.constructor();
    else objClone = new obj.constructor(obj.valueOf());
    for (var key in obj) {
      if (objClone[key] != obj[key]) {
        if (typeof (obj[key]) == 'object') {
          objClone[key] = cm.cloneObj(obj[key]);
        }
        else {
          objClone[key] = obj[key];
        }
      }
    }
    objClone.toString = obj.toString;
    objClone.valueOf = obj.valueOf;
    return objClone;
  },
  cloneObj2: function (obj) {
    var objClone = {};
    return $.extend(objClone, obj);
    return objClone;
  },
  dtToLYMDMS:function(l) {
    var date = l == null ? new Date() : new Date(l);
    var seperator1 = "-";
    var seperator2 = ":";
    var month = date.getMonth() + 1;
    var strDate = date.getDate();
    if (month >= 1 && month <= 9) {
      month = "0" + month;
    }
    if (strDate >= 0 && strDate <= 9) {
      strDate = "0" + strDate;
    }
    var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
      + " " + date.getHours() + seperator2 + date.getMinutes()
      + seperator2 + date.getSeconds();
    return currentdate;
  },
  dtToLong: function () {
    return new Date().getTime()
  },
  setObjDateStr:function (arr) {
    for (var i=0; i<arr.length; i++ ){
      for ( var j= 1; j<arguments.length; j++ ){
        if (arr[i][arguments[j]] != null){
          arr[i][arguments[j]+"Str"] = cm.dtToLYMDMS(arr[i][arguments[j]]);
        }
      }
    }
  },
  getUrlData: function (url) {
    var dd = "";
    $.ajax({
      type: "GET",
      url: url,
      dataType: 'json',
      async: false,
      success: function (data) {
        dd = data;
      }
    });
    return dd;
  },
  getFontDefaultGcArr: function () {
    var fontarr = new Array('normal', 'normal', '14.6667px', 'Calibri');
    return fontarr;
  },
  getFontStr: function (src, fontname, fontsize, fontweight, fontstyle) {
    if (fontname == null && fontsize == null && fontweight == null && fontstyle == null)
      return null;
    var arrVal = cm.getFontDefaultGcArr();
    if (src != null && src.length > 0) {
      var srcArr = src.split(" ");
      var cur = 0;
      for (var i = srcArr.length - 1; i >= 0; i--) {
        arrVal[3 - cur] = srcArr[i];
        cur++;
      }
    }

    if (fontname != null)
      arrVal[3] = fontname;
    if (fontsize != null)
      arrVal[2] = fontsize;
    if (fontweight != null)
      arrVal[1] = fontweight;
    if (fontstyle != null)
      arrVal[0] = fontstyle;
    return arrVal.join(" ");
  },
  getFontSize: function (src) {
    var arr = src.split(" ");
    if (arr.length >= 2) {
      return arr[arr.length - 2];
    }
    return null;
  },
  getFontBold: function (src) {
    var arr = src.split(" ");
    if (arr.length >= 3) {
      return arr[arr.length - 3];
    }
    return null;
  },
  getFontStyle: function (src) {
    var arr = src.split(" ");
    if (arr.length >= 4) {
      return arr[0];
    }
    return null;
  },
  getFontName: function (src) {
    var arr = src.split(" ");
    if (arr.length >= 1) {
      return arr[arr.length - 1];
    }
    return null;
  },
  arrMergeToSrc: function (srcArr, dstArr) {
    var len = a.length;
    for (var i = 0; i < len; i++) {
      if (i >= dstArr.length) {
        break;
      }
      if (dstArr[i] != null) {
        srcArr[i] = dstArr[i];
      }
    }
    return srcArr;
  },
  ajax: function (url, data) {
    var ret;
    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: 'text',
      async: false,
      success: function (retD) {
        ret = cm.obj(retD);
      }

    });
    return ret;
  },
  ajaxJBody: function (url, data) {
    var ret;
    $.ajax({
      type: "POST",
      url: url,
      data: data,
      dataType: 'json',
      contentType:"application/json",
      async: false,
      success: function (retD) {
        ret = retD;
      },
      error:function (XMLHttpRequest, textStatus, errorThrown) {
        var err = "ree";
      }

    });
    return ret;
  },
  dataOk: function (data) {
    return data != null && data.code >0;
  },
  dataNotOk: function (data) {
    return !this.dataOk(data);
  },
  dataMsg: function (data) {
    return data.msg;
  },
  dataVal: function (data) {
    return data.data;
  }
};

function cpWildStr() {
  this.type = 0;
  this.str="";
}

cpWildStr.prototype = {
  parseStr: function (str) {
    if (str.charAt(0) == '*') {
      this.str = str.substring(1, str.length);
      this.type = 1;
    }
    else if (str.charAt(str.length - 1) == '*') {
      this.str = str.substring(0, str.length - 1);
      this.type = 2;
    }
    else {
      this.str = str;
      this.type = 0;
    }
    return this;
  },
  matchStr:function (s) {
    if (this.type == 0) {
      return s == this.str;
    }
    else if (this.type == 1) {//*f
      return cm.strFindSubfix(s, this.str) > -1;
    }
    else if (this.type == 2) {//f*
      return s.indexOf(this.str) == 0;
    }
  }
};

//cellplus main class
function cellPlus(divObj) {
  this.rawO = new GcSpread.Sheets.Spread(divObj);
  this.tmpData = {};
  this.tmpData.deletedDids = {};
  //if (typeof divObj === "object") {
  //    this.rawO = new GcSpread.Sheets.Spread(divObj);
  //    if (typeof initObj === "object") {
  //        this.showCellJs(true);
  //    }
  //}
}

cellPlus.prototype = {
  showCellJs: function (bval) {
    var v = bval ? "block" : "none";
    this.rawO.style.display = v;
  },
  bind: function (obj, func) {
    this.rawO.bind(obj, func);
  },
  saveToJson: function () {
    return this.rawO.toJSON(false);
  },
  saveToJsonStr: function () {
    return cm.str(this.saveToJson());
  },
  canUserDragFill: function (v) {
    if (v == null) {
      return this.rawO.canUserDragFill();
    }
    else {
      return this.rawO.canUserDragFill(v);
    }
  },
  //defaultDragFillType:function(v){
  //    if (v == null) {
  //        var autocell = cpUtil.getAutoFillToCell(v);
  //        return autocell;
  //    }
  //    else {
  //        var auto = cpUtil.getAutoFillToGc(v);
  //        this.rawO.defaultDragFillType(auto);
  //    }
  //},
  canUserDragDrop: function (v) {
    if (v == null) {
      return this.rawO.canUserDragDrop();
    }
    else {
      return this.rawO.canUserDragDrop(v);
    }
  },
  canUserEditFormula: function (v) {
    if (v == null) {
      return this.rawO.canUserEditFormula();
    }
    else {
      return this.rawO.canUserEditFormula(v);
    }
  },
  loadFromUrl: function () {

  },
  destroy: function () {
    this.rawO.destroy();
  },
  loadFromJson: function (obj) {
    this.rawO.fromJSON(obj);
  },
  loadFromJsonStr: function (str) {
    this.loadFromJson(cm.obj(str));
  },
  EnableAutoFit: function (iVal) {
    this.rawO.EnableAutoFit(iVal);
  },
  OpenFile: function (fileName, pwd) {
    this.rawO.OpenFile(fileName, pwd);
  },
  SetShowFormula: function (iVal) {
    this.rawO.SetShowFormula(iVal);
  },
  GetRows: function (sheet) {
    this.rawO.GetRows(sheet);
  },
  CalculateSheet2: function (sheet) {
    this.rawO.CalculateSheet2(sheet);
  },
  GetCellNote: function (row, col, sheet) {
    this.rawO.GetCellNote(col, row, sheet);
  },
  SetColRowManualFit: function (row, col, sheet, fitType) {
    this.rawO.SetColRowManualFit(col, row, sheet, fitType);
  },
  setColWidth: function (type, col, sheet, width) {
    var gcsheet = this.igetsheet(sheet);
    gcsheet.setColumnWidth(col - 1, width);
  },
  setRowHeight: function (type, row, sheet, height) {
    var gcsheet = this.igetsheet(sheet);
    gcsheet.setRowHeight(row - 1, height);
  },
  AllowExtend: function (bval) {
    this.rawO.AllowExtend(bval);
  },
  GetCurrentRow: function () {
    return this.rawO.getActiveSheet().getActiveRowIndex();
  },
  InsertRow: function (iRow, iCount, iSheet) {
    this.getSheet(iSheet).addRows(iRow - 1, iCount);
  },
  GetCols: function (iSheet) {
    return this.getSheet(iSheet).getColumnCount();
  },
  addSelection: function (r1, c1, r2, c2) {
    return this.rawO.addSelection(r1-1, c1-1, r2-r1+1,c2-c1+1);
  },
  clearSelection: function () {
    return this.rawO.clearSelection();
  },
  GetTreeNodeType: function (row, col, sheet) {
    return this.rawO.GetTreeNodeType(col, sheet, row);
  },
  IsRowHidden: function (row, sheet) {
    return this.rawO.IsRowHidden(row, sheet);
  },
  SetRowUnhidden: function (row1, row2) {
    return this.rawO.SetRowUnhidden(row1, row2);
  },
  ClearArea: function (row1, col1, row2, col2, sheet, iOption) {
    return this.rawO.ClearArea(col1, row1, col2, row2, sheet, iOption);
  },
  GetCellInput: function (row, col, sheet) {
    return this.rawO.GetCellInput(col, row, sheet);
  },
  MoveToCell: function (row, col) {
    return this.rawO.MoveToCell(col, row);
  },
  GetRadioCellString: function (row, col, sheet) {
    return this.rawO.GetRadioCellString(col, row, sheet);
  },
  setCellDouble: function (row, col, sheet, dval) {
    var gcsheet = this.igetsheet(sheet);
    gcsheet.setValue(row - 1, col - 1, dval);
  },
  setCellString: function (row, col, sheet, sval) {
    var gcsheet = this.igetsheet(sheet);
    gcsheet.setText(row - 1, col - 1, sval);
  },
  setCellValueJs: function (row, col, sheet, obj) {
    var gcsheet = this.igetsheet(sheet);
    gcsheet.setValue(row - 1, col - 1, obj);
  },
  getCellValueJs: function (row, col, sheet) {
    var gcsheet = this.igetsheet(sheet);
    return gcsheet.getValue(row - 1, col - 1);
  },
  getCellDouble: function (row, col, sheet, dval) {
    var gcsheet = this.igetsheet(sheet);
    gcsheet.getValue(row - 1, col - 1);
  },
  getCellString: function (row, col, sheet, sval) {
    var gcsheet = this.igetsheet(sheet);
    return gcsheet.getText(row - 1, col - 1);
  },
  RemoveTreeNode: function (sheet, sTreeNodeName) {
    return this.rawO.RemoveTreeNode(sheet, sTreeNodeName);
  },
  SaveEdit: function () {
    return this.rawO.SaveEdit();
  },
  SetSuperVldType: function () {
    return this.rawO.SetSuperVldType();
  },
  CheckAllValidCell: function (iType) {
    return this.rawO.CheckAllValidCell(iType);
  },
  IsCellCanEdit: function (row, col, sheet) {
    return this.rawO.IsCellCanEdit(col, row, sheet);
  },
  StartEdit: function (row, col) {
    return this.rawO.StartEdit(col, row);
  },

  ShowFileDlg: function (isOpenFile, defFileExt, initFileName, extFilter) {
    return this.rawO.cellPlus.ShowFileDlg(isOpenFile, defFileExt, initFileName, extFilter);
  },
  ShowImageDlg: function () {
    return this.rawO.cellPlus.ShowImageDlg();
  },
  SaveSheetToFile: function (fileName, pwd, sheetIndex, count) {
    return this.rawO.cellPlus.SaveSheetToFile(fileName, pwd, sheetIndex, count);
  },

  FindDialog: function (iWithReplaceButton) {
    return this.rawO.FindDialog(iWithReplaceButton);
  },
  CopyRange: function (row1, col1, row2, col2) {
    return this.rawO.CopyRange(col1, row1, col2, row2);
  },
  Paste: function (row1, col1, row2, col2) {
    return this.rawO.Paste(col1, row1, col2, row2);
  },
  currentSheetIndex: function () {
    return this.rawO.getActiveSheetIndex();
  },
  currentSheet: function () {
    return this.rawO.getActiveSheet();
  },
  currentSheet2: function () {
    var index = this.currentSheetIndex();
    return this.getSheet(index);
  },
  deleteCustomVar: function (vname,sheet) {
    var wldstr = new cpWildStr().parseStr(vname);
    if ( wldstr.type == 0 ){
      this.rawO.removeCustomName(vname);
    }
    else {
      var names = this.getGcSheet(sheet).getCustomNames();
      for (var i = 0; i < names.length; i++) {
        var name = names[i].getName();
        var expression = names[i].getExpression();
        if ( wldstr.matchStr(name)){
          this.rawO.removeCustomName(name);
        }
      }
    }
  },
  customVar: function (myname, val) {
    if (val == null) {
      var cname = this.rawO.getCustomName(myname);
      if (cname != null) {
        return cname.getExpression().name;
      }
      return "";
    }
    else {
      this.rawO.addCustomName(myname, "=" + val, 0, 0);
    }
  },
  selection: function () {
    var cprg = this.getNewRange();
    var o = this.currentSheet().getSelections();
    for (var i = 0; i < o.length; i++) {
      var rg = new icprange();
      rg.setRg(o[i].row + 1, o[i].col + 1, o[i].row + o[i].rowCount, o[i].col + o[i].colCount, this.currentSheetIndex())
      cprg.iappend(rg);
    }
    return cprg;
  },
  getRange: function (r1, c1, r2, c2, sheet) {
    return this.getNewRange(r1, c1, r2, c2, sheet);
  },
  getRangeByCustomVar: function (wildstr, sheet) {
    if (sheet == null) {
      sheet = this.currentSheetIndex();
    }
    var names = this.getGcSheet(sheet).getCustomNames();
    var wldstr = new cpWildStr().parseStr(wildstr);
    var cpRg = this.getNewRange();
    for (var i = 0; i < names.length; i++) {
      var name = names[i].getName();
      var expression = names[i].getExpression();
      if ( wldstr.matchStr(name)){
        var icp = cpUtil.gcRgToIcp(expression, sheet);
        icp.varName = name;
        if (icp != null)
          cpRg.iappend(icp);
      }
    }
    return cpRg;
  },
  getRawObj: function () {
    return this.rawO;
  },
  getGcSheet: function (index) {
    return this.rawO.getSheet(index);
  },
  getSheet: function (index) {
    var s = new cpSheet();
    s.isetsheet(index, this);
    return s;
  },
  getSheetByVar: function (name) {
    var cpSht = null;
    this.foreachSheetJs(function (cpSheet, idx) {
      if (cpSheet.customVar() == name) {
        cpSht = cpSheet;
        return;
      }
    });
    return cpSht;
  },
  tabStripVisible: function (v) {
    if (v == null) {
      return this.rawO.tabStripVisible();
    }
    else {
      return this.rawO.tabStripVisible(v);
    }
  },
  newTabVisible: function (v) {
    if (v == null) {
      return this.rawO.newTabVisible();
    }
    else {
      return this.rawO.newTabVisible(v);
    }
  },
  addSheet: function (index, sheetName) {
    var sheet = new GcSpread.Sheets.Sheet();
    sheet.setName("sheetName");
    this.rawO.addSheet(index, sheet);
    return this.getSheet(index);
  },
  foreachSheetJs: function (call) {
    for (var i = 0; i < this.getSheetCount(); i++) {
      call(this.getSheet(i), i);
    }
  },
  getSheetCount: function () {
    return this.rawO.getSheetCount();
  },
  igetsheet: function (index) {
    return this.rawO.getSheet(index);
  },
  getNewRange: function (r1, c1, r2, c2, sheet) {
    var cprg = new cpRange();
    cprg.isetcpl(this);
    if (r1 != null && c1 != null && sheet != null) {
      if (r2 == null && c2 == null) {
        r2 = r1;
        c2 = c1;
      }
      cprg.iresetrg(new icprange().setRg(r1, c1, r2, c2, sheet, 0));
    }
    return cprg;
  },
  stopDraw: function () {
    this.rawO.isPaintSuspended(true);
  },
  resumDraw: function () {
    this.rawO.isPaintSuspended(false);
  }
}
//end cellplus

//Range  class
function cpRange() {
  this.cpl = null;
  this.rgArr = new Array(); //instance has two different flag
}

cpRange.prototype = {
  readonly:function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.locked(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.itogcrg().locked();
    }
  },
  iappend: function (icp) {
    this.rgArr.push(icp);
  },
  iresetrg: function (icp) {
    this.rgArr = [];
    this.iappend(icp);
  },
  isetcpl: function (cpl) {
    this.cpl = cpl;
  },
  igeticp: function () {
    return this.rgArr[0];
  },
  isheetindex: function () {
    return this.rgArr[0].sheet;
  },
  itogcrg: function () {
    var icp = this.igeticp();
    return cpUtil.icpToGcCells(this.cpl, icp);
  },
  itogcrgTL: function () {
    var icp = this.igeticp();
    this.parentSheet().getCells(icp.r1, icp.c1, icp.r1, icp.c1);
  },
  resetByIcp:function (icp) {
    this.rgArr = [];
    this.appendByIcp(icp);
    return this;
  },
  appendByIcp:function (icp) {
    this.rgArr.push(icp);
    return this;
  },
  setCpl:function (cpl) {
    this.cpl = cpl;
    return this;
  },
  resetByOffset: function (offr1, offc1, offr2, offc2) {
    var icp = this.igeticp();
    icp.r1 += offr1;
    icp.r2 += offr2;
    icp.c1 += offc1;
    icp.c2 += offc2;
  },
  tag: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.tag(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.itogcrg().tag();
    }
  },
  cellType: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.cellType(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().cellType();
    }
  },
  formatter: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.formatter(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().formatter();
    }
  },
  borderLeft: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.borderLeft(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().borderLeft();
    }
  },
  borderTop: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.borderTop(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().borderTop();
    }
  },
  borderRight: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.borderRight(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().borderRight();
    }
  },
  borderBottom: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.borderBottom(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().borderBottom();
    }
  },
  hAlign: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.hAlign(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().hAlign();
    }
  },
  vAlign: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.vAlign(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().vAlign();
    }
  },
  font: function (name, size, fontweight, fontstyle) {
    if (name != null || size != null || fontweight != null || fontstyle != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachCell(function (cpl, rg) {
        var gcCells = cpUtil.icpToGcCells(cpl, rg.igeticp());
        var str = gcCells.font();
        str = cm.getFontStr(str, name, size, fontweight, fontstyle);
        gcCells.font(str);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().font();
    }
  },
  wordWrap: function (v) {
    if (v != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.wordWrap(v);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().wordWrap();
    }
  },
  merge: function (mg) {
    this.foreachJs(function (rg, index) {
      rg.getCurSheet().merge(rg.r1(), rg.c1(), rg.r2(), rg.c2());
    });
  },
  unMerge: function () {
    this.parentSheet().isPaintSuspended(true);
    this.foreachCell(function (cpl, rg) {
      rg.getCurSheet().unMerge(rg.r1(), rg.c1());
    });
    this.parentSheet().isPaintSuspended(false);
  },
  insertRow: function (count) {
    this.getCurSheet().insertRow(this.r1(), count);
  },
  insertCol: function (count) {
    this.getCurSheet().insertCol(this.c1(), count);
  },
  deleteRow: function () {
    this.foreachJs(function (rg, index) {
      rg.getCurSheet().deleteRow(rg.r1(), rg.rowCount());
    });
  },
  deleteCol: function () {
    this.foreachJs(function (rg, index) {
      rg.getCurSheet().deleteCol(rg.c1(), rg.colCount());
    });
  },
  foreColor: function (clr) {
    if (clr != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.foreColor(clr);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().foreColor();
    }
  },
  backColor: function (clr) {
    if (clr != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.backColor(clr);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().backColor();
    }
  },
  textDecoration: function (obj) {
    if (obj != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachCell(function (cpl, rg) {
        var gcCells = cpUtil.icpToGcCells(cpl, rg.igeticp());
        gcCells.textDecoration(obj);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      var ff = this.getLTRg().itogcrg().textDecoration();
      return ff;
    }
  },
  rowCount: function () {
    var count = 0;
    for (var i = 0; i < this.rgArr.length; i++) {
      count += this.rgArr[i].rowCount();
    }
    return count;
  },
  colCount: function () {
    var count = 0;
    for (var i = 0; i < this.rgArr.length; i++) {
      count += this.rgArr[i].colCount();
    }
    return count;
  },
  c1: function (v) {
    if (v != null) {
      this.igeticp().c1 = v;
    }
    return this.igeticp().c1;
  },
  r1: function (v) {
    if (v != null) {
      this.igeticp().r1 = v;
    }
    return this.igeticp().r1;
  },
  c2: function (v) {
    if (v != null) {
      this.igeticp().c2 = v;
    }
    return this.igeticp().c2;
  },
  r2: function (v) {
    if (v != null) {
      this.igeticp().r2 = v;
    }
    return this.igeticp().r2;
  },
  s: function (v) {
    if (v != null) {
      this.igeticp().sheet = v;
    }
    return this.igeticp().sheet;
  },
  text: function (val) {

    if (val != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.text(val);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().text();
    }

  },
  value: function (val) {
    if (val != null) {
      this.parentSheet().isPaintSuspended(true);
      this.foreachJsInter(function (cpl, icp, index) {
        var gcCells = cpUtil.icpToGcCells(cpl, icp);
        gcCells.value(val);
      });
      this.parentSheet().isPaintSuspended(false);
    }
    else {
      return this.getLTRg().itogcrg().value();
    }
  },
  getArea: function (index) {
    if (index >= 0 && index < this.rgArr.length) {
      var cp = this.cpl.getNewRange();
      cp.iresetrg(this.rgArr[index]);
      return cp;
    }
    else {
      return null;
    }
  },
  foreachJs: function (callback) {
    for (var i = 0; i < this.areaCount(); i++) {
      if (callback != null) {
        callback(this.getArea(i), i);
      }
    }
  },
  foreachJsInter: function (callback) {
    for (var i = 0; i < this.areaCount(); i++) {
      if (callback != null) {
        callback(this.cpl, this.rgArr[i], i);
      }
    }
  },
  foreachCell: function (callback) {
    for (var i = 0; i < this.areaCount(); i++) {
      var area = this.getArea(i);
      for (var j = area.r1(); j <= area.r2(); j++) {
        for (var m = area.c1(); m <= area.c2(); m++) {
          var rg = this.cpl.getNewRange(j, m, j, m, area.s());
          if (callback != null) {
            callback(this.cpl, rg, j);
          }
        }
      }
    }
  },
  areaCount: function () {
    return this.rgArr.length;
  },
  makeSureItem: function (num) {
    if (this.rgArr.length < num) {
      var want = num - this.rgArr.length;
      for (var i = 0; i < want; i++) {
        this.rgArr.push(new icprange());
      }
    }
  },
  customVar: function (v) {
    if (v == null) {
      var icp = this.igeticp();
      return icp.varName;
    }
    else {
      var icp = this.igeticp();
      var refstr = cpUtil.icpToRefStr(icp);
      var o = this.cpl.getGcSheet(this.isheetindex());
      o = o.addCustomName(v, "=" + refstr, 0, 0);
      return 0;
    }
  },
  deleteCustomVar: function (delRg) {
    var o = this.cpl.getGcSheet(this.isheetindex());
    for (var i = this.rgArr.length - 1; i >= 0; i--) {
      o.removeCustomName(this.rgArr[i].varName);
      if (delRg == true) {
        this.rgArr.pop();
      }
    }
  },
  getRangeByCustomVar: function (wildstr) {
    return this.cpl.getRangeByCustomVar(wildstr, this.isheetindex());
  },
  getLTRg: function () {
    var icp = cm.cloneObj(this.igeticp());
    icp.setToEnd();
    var rg = this.cpl.getNewRange();
    rg.iappend(icp);
    return rg;
  },
  getRBRg: function () {
    var icp = cm.cloneObj(this.igeticp());
    icp.c1 = icp.c2;
    icp.r1 = icp.r2;
    var rg = this.cpl.getNewRange();
    rg.iappend(icp);
    return rg;
  },
  toRgStr: function () {
    var str = "";
    for (var i = 0; i < this.rgArr.length; i++) {
      str += cpUtil.icpToRefStr(this.rgArr[i]);
      if (i < this.rgArr.length - 1)
        str += ",";
    }
    return str;
  },
  parentSheet: function () {
    return this.cpl.getGcSheet(this.isheetindex());
  },
  rawSheet: function () {
    return this.cpl.getGcSheet(this.isheetindex());
  },
  getCurSheet: function () {
    return this.cpl.getSheet(this.isheetindex());
  },
  cloneNew: function () {
    var cp = this.cpl.getNewRange();
    for (var i = 0; i < this.rgArr.length; i++) {
      var icp = new icprange();
      icp.initBy(this.rgArr[i]);
      cp.iappend(icp);
    }
    return cp;
  },
  autoFill: function (count, direction, func) {
    if (count <= 0)
      return;
    var icp = cm.cloneObj(this.igeticp());
    var start = cpUtil.icpToGcRange(icp);
    var sel = this.cpl.selection();
    icp.offsetMulti(count, direction);
    icp.mergeIcp(this.igeticp());
    var end = {};
    this.parentSheet().isPaintSuspended(true);
    var dragFillExtent = {};
    switch (direction) {
      case 1:
        icp.c2 = this.c1() - 1;
        end = cpUtil.icpToGcRange(icp);
        dragFillExtent = {
          startRange: start, fillRange: end, autoFillType: GcSpread.Sheets.AutoFillType.FillFormattingOnly,
          fillDirection: GcSpread.Sheets.FillDirection.Left
        };
        break;
      case 2:
        icp.r2 = this.r1() - 1;
        end = cpUtil.icpToGcRange(icp);
        dragFillExtent = {
          startRange: start, fillRange: end, autoFillType: GcSpread.Sheets.AutoFillType.FillFormattingOnly,
          fillDirection: GcSpread.Sheets.FillDirection.Up
        };
        break;
      case 3:
        icp.c1 = this.c2() + 1;
        end = cpUtil.icpToGcRange(icp);
        dragFillExtent = {
          startRange: start, fillRange: end, autoFillType: GcSpread.Sheets.AutoFillType.FillFormattingOnly,
          fillDirection: GcSpread.Sheets.FillDirection.Right
        };
        break;
      case 4:
        icp.r1 = this.r1() + 1;
        end = cpUtil.icpToGcRange(icp);
        dragFillExtent = {
          startRange: start, fillRange: end, autoFillType: GcSpread.Sheets.AutoFillType.FillFormattingOnly,
          fillDirection: GcSpread.Sheets.FillDirection.Down
        };
        break;
    }
    if ( func != null ){
      var cpRg = new cpRange();
      cpRg.resetByIcp(icp).setCpl(this.cpl);
      func(cpRg);
    }
    var action = new GcSpread.Sheets.UndoRedo.DragFillUndoAction(this.parentSheet(), dragFillExtent);
    this.parentSheet().doCommand(action);
    sel.setSelected();
    this.parentSheet().isPaintSuspended(false);
  },
  isRgInThis: function (cpRg) {
    return cpUtil.isRgInRg(this, cpRg);
  },
  isRgEqualThis: function (cpRg) {
    return cpUtil.equalRg(this, cpRg);
  },
  htRgGetIndex: function (cpRg) {
    if (!this.isRgInThis(cpRg)) {
      return -1;
    }
    var ret = this.htRgGetItemContainRg(cpRg, null);
    if (ret == null) {
      return -1;
    }
    return ret.cur;
  },
  htRgInsertItem: function (cpRg, num, headRg, func) {
    var retCom = this.htRgGetItemContainRg(cpRg, headRg);
    if (retCom == null) {
      return;
    }
    var cusName = this.customVar();
    this.deleteCustomVar();

    var dir = 4;
    if (retCom.curHTRgOne.isRgEqualThis(retCom.headRg.mergeToOne())) {
      var startRow = retCom.curHTRgOne.r2() + 1;
      this.getCurSheet().insertRow(startRow, num * retCom.curHTRgOne.rowCount());
      retCom.curHTRgOne.autoFill(num, dir,function (dst) {
        dst.readonly(false);
      });
      this.resetByOffset(0, 0, num * retCom.curHTRgOne.rowCount(), 0);
      if (func != null) {
        func(retCom, num, dir);
      }
    } else {
      dir = 2;
      var startRow = retCom.curHTRgOne.r1();
      this.getCurSheet().insertRow(startRow, num * retCom.curHTRgOne.rowCount());
      retCom.curHTRgOne.resetByOffset(num, 0, num, 0);
      retCom.curHTRgOne.autoFill(num, dir, function (dst) {
        dst.readonly(false);
      });
      this.resetByOffset(0, 0, num * retCom.curHTRgOne.rowCount(), 0);
    }

    this.customVar(cusName);
    if (func != null) {
      func(retCom, num, dir);
    }
  },
  htRgAppendItem: function (cpRg, num, headRg, func) {
    var retCom = this.htRgGetItemContainRg(cpRg, headRg);
    if (retCom == null) {
      return;
    }
    var cusName = this.customVar();
    this.deleteCustomVar();

    var dir = 4;
    var startRow = retCom.curHTRgOne.r2() + 1;
    this.getCurSheet().insertRow(startRow, num * retCom.curHTRgOne.rowCount());
    retCom.curHTRgOne.autoFill(num, dir, function (dst) {
      dst.readonly(false);
    });
    this.resetByOffset(0, 0, num * retCom.curHTRgOne.rowCount(), 0);
    this.customVar(cusName);

    if (func != null) {
      func(retCom, num, dir);
    }
  },
  htRgDeleteItem: function (cpRg, headRg, func) {
    var retCom = this.htRgGetItemContainRg(cpRg, headRg);
    if (retCom == null) {
      return null;
    }
    if (func != null) {
      var ret = func(retCom);
      //==1 continue, 0 返回失败
      if (ret == 0) {
        return -1;
      }
    }
    if (this.isRgEqualThis(retCom.headRg.mergeToOne())) {
      //todo
    }
    else {
      retCom.curHTRgOne.deleteRow();
      this.resetByOffset(0, 0, retCom.curHTRgOne.rowCount() * -1, 0);
      var cusName = this.customVar();
      this.deleteCustomVar();
      this.customVar(cusName);
    }
  },
  htRgGetItemContainRg: function (cpRg, headRg) {
    var hRg = headRg;
    if (hRg == null) {
      hRg = this.htRgGetHead();
    }
    var retRg = null;
    this.htRgForeachItem(hRg, null, 1, function (curHTRg, offsetArr, cur, headRg) {
      if (curHTRg.isRgInThis(cpRg)) {
        retRg = {};
        retRg.curHTRgOne = curHTRg;
        retRg.cur = cur;
        retRg.offsetArr = offsetArr;
        retRg.headRg = headRg;
        return 1;
      }
    });
    return retRg;
  },
  htRgGetItemValInter: function (idx, offsetArr, headRg, func) {
    var offRg = this.cpl.getNewRange()
    offRg.makeSureItem(1);
    var oneRg = new cpRange();
    oneRg = headRg.mergeToOne();

    var outObj = {};
    oneRg.offsetBlock(idx - 1, 0);
    for (var j = 0; j < offsetArr.length; j++) {
      oneRg.genOffsetRg(offsetArr[j], offRg);
      var jname = cm.strSplitIdx(headRg.rgArr[j].varName, ":", 2);
      outObj[jname] = offRg.text();
      if (func != null) {
        func(outObj, j, jname, offRg, idx);
      }
    }
    return outObj;
  },
  htRgGetItemVal: function (idx, headRg) {
    var hRg = headRg;
    if (hRg == null) {
      hRg = this.htRgGetHead();
    }
    var offsetArr = cpUtil.getOffsetToArr(hRg.rgArr, hRg.mergeToOne().igeticp());
    return this.htRgGetItemValInter(idx, offsetArr, hRg);
  },
  htRgGetAllVal: function (headRg, func) {
    var hRg = headRg;
    if (hRg == null) {
      hRg = this.htRgGetHead();
    }

    var num = this.htRgGetItemCount(hRg, 4);
    var offsetArr = cpUtil.getOffsetToArr(hRg.rgArr, hRg.mergeToOne().igeticp());
    var columns = [];
    for (var i = 1; i <= num; i++) {
      var data = this.htRgGetItemValInter(i, offsetArr, hRg, func);
      columns.push(data);
    }
    return columns;
  },
  htRgReset: function (num, headRg) {
    var hRg = headRg;
    if (hRg == null) {
      hRg = this.htRgGetHead();
    }

    var curCnt = this.htRgGetItemCount(hRg, 4);
    if (curCnt > num) {
      var delNum = (curCnt - num);
      delNum = delNum * hRg.mergeToOne().rowCount();
      var start = this.r2() - delNum + 1;
      this.getCurSheet().deleteRow(start, delNum);

      this.resetByOffset(0, 0, delNum * -1, 0);
      var cusName = this.customVar();
      this.deleteCustomVar();
      this.customVar(cusName);
    }
    else {
      var addNum = num - curCnt;
      this.htRgInsertItem(hRg.getRBRg(), addNum, headRg);
    }

  },
  htRgFillVal: function (dataArr, func) {

    var headRg = this.htRgGetHead();
    var oneRg = headRg.mergeToOne();
    var offsetArr = cpUtil.getOffsetToArr(headRg.rgArr, oneRg.igeticp());
    var colNum = oneRg.colCount();
    var rowNum = oneRg.rowCount();

    var dataLen = dataArr.length;
    if (dataLen > 1) {
      this.htRgInsertItem(headRg, dataLen - 1, headRg);
    }

    var offRg = cpUtil.getNewRange(this.cpl);
    offRg.makeSureItem(1);

    for (var i = 0; i < dataLen; i++) {
      if (i > 0) {
        oneRg.offsetBlock(1, 0);
      }
      for (var j = 0; j < offsetArr.length; j++) {
        oneRg.genOffsetRg(offsetArr[j], offRg);
        var colName = cm.strSplitIdx(headRg.rgArr[j].varName, ":", 2);
        offRg.value(dataArr[i][colName]);
        if (func != null) {
          func(offRg, j, colName, dataArr[i]);
        }
      }
    }
  },
  htRgForeachItem: function (headRg, viewRg, dir, func) {
    var oneRg = headRg.mergeToOne();
    var offsetArr = cpUtil.getOffsetToArr(headRg.rgArr, oneRg.igeticp());
    var colNum = oneRg.colCount();
    var rowNum = oneRg.rowCount();

    var cur = 0;
    while (true) {
      oneRg.offsetBlock(cur > 0 ? 1 : 0, 0);
      cur++;
      if (this.isRgInThis(oneRg.getLTRg())) {
        if (func != null) {
          var ret = func(oneRg, offsetArr, cur, headRg);
          if (ret == 1)
            break;
        }
      }
      else {
        break;
      }
    }
  },
  htRgGetHead: function (Prefix) {
    if (Prefix == null) {
      Prefix = this.customVar();
      var arr = cm.strSplit(this.customVar(), ":");
      Prefix = arr[0] + ":" + arr[2] + ":*";
    }
    var rg = this.getRangeByCustomVar(Prefix);
    return rg;
  },
  htRgDefine: function (name) {
    this.customVar(name);
  },
  htRgGetItemCount: function (headRg, dir) {
    var hRg = headRg;
    if (hRg == null) {
      hRg = this.htRgGetHead();
    }
    if (dir == 4) {//down
      var rowCnt = hRg.mergeToOne().rowCount();
      var rows = this.rowCount() / rowCnt;
      return rows;
    }
    else if (dir == 3) {//right

    }
  },
  fillRowDataJs: function (varPrefix, jsonObj) {
    if (jsonObj instanceof Array) {
      var oneRg = this.mergeToOne();
      var offsetArr = cpUtil.getOffsetToArr(this.rgArr, oneRg.igeticp());
      var colNum = oneRg.colCount();
      var rowNum = oneRg.rowCount();

      var dataLen = jsonObj.length;
      if (dataLen > 1) {
        oneRg.autoFill(dataLen - 1, 1, function (dst) {
          dst.readonly(false);
        });
      }

      var offRg = cpUtil.getNewRange(this.cpl);
      offRg.makeSureItem(1);

      for (var i = 0; i < dataLen; i++) {
        if (i > 0) {
          oneRg.offsetBlock(1, 0);
        }
        for (var j = 0; j < offsetArr.length; j++) {
          oneRg.genOffsetRg(offsetArr[j], offRg);
          var jname = this.rgArr[j].varName.substring(varPrefix.length);
          offRg.value(jsonObj[i][jname]);
        }
      }
      this.cpl.customVar(varPrefix + "NumFilled", dataLen);

    }
    else if (jsonObj instanceof Object) {
      var arrJ = [];
      arrJ.push(jsonObj);
      this.fillRowDataJs(varPrefix, arrJ);
    }
    else {
      alert("obj type error!");
    }
  },
  getRowDataJs: function (varPrefix, idx) {
    var oneRg = this.mergeToOne();
    var offsetArr = cpUtil.getOffsetToArr(this.rgArr, oneRg.igeticp());
    var colNum = oneRg.colCount();
    var rowNum = oneRg.rowCount();

    var dataLen = this.cpl.customVar(varPrefix + "NumFilled");
    if (idx > dataLen)
      return null;
    var offRg = new cpRange();
    offRg.makeSureItem(1);

    if (idx == -1) {
      var outArr = [];
      for (var i = 0; i < dataLen; i++) {
        oneRg.offsetBlock(i, 0);
        var outObj = {};
        for (var j = 0; j < offsetArr.length; j++) {
          oneRg.genOffsetRg(offsetArr[j], offRg);
          var jname = this.rgArr[j].substring(varPrefix.length);
          outObj[jname] = offRg.text();
        }
        outArr.push(outObj);
      }
      return outArr;
    }
    else {
      var outObj = {};
      oneRg.offsetBlock(idx - 1, 0);
      for (var j = 0; j < offsetArr.length; j++) {
        oneRg.genOffsetRg(offsetArr[j], offRg);
        var jname = this.rgArr[j].substring(varPrefix.length);
        outObj[jname] = offRg.text();
      }
      return outObj;
    }
  },
  mergeToOne: function () {
    var cp = this.cpl.getNewRange();
    var icp = new icprange();
    icp.mergeIcpArr(this.rgArr);
    cp.iappend(icp);
    return cp;
  },
  setSelected: function(){
    if ( this.isheetindex() == this.cpl.currentSheetIndex() ) {
      this.rawSheet().clearSelection();
      this.rawSheet().addSelection(this.r1()-1, this.c1()-1, this.rowCount(), this.colCount());
    }
  },
  offsetBlock: function (rowCount, colCount) {
    for (var i = 0; i < this.rgArr.length; i++) {
      this.rgArr[i].offsetBlock(rowCount, colCount);
    }
    return this;
  },
  genOffsetRg: function (icpOffset, outRg) {
    if (outRg == null) {
      outRg = this.cpl.getNewRange();
      outRg.makeSureItem(1);
    }
    var topIcp = this.igeticp();
    topIcp.genOffsetRg(icpOffset, outRg.igeticp());
    return outRg;
  }
};

//Sheet  class
function cpSheet() {
  this.cpl = null;
  this.index = 0;
  this.sheetObj = null;
}

cpSheet.prototype = {
  readonly:function (b) {
    if(b){
      return this.sheetObj.setIsProtected(b);
    }
    else {
      return this.sheetObj.getIsProtected();
    }
  },
  isetcpl: function (cpl) {
    this.cpl = cpl;
  },
  iresetsheet: function (i) {
    this.index = i;
    this.sheetObj = this.cpl.getGcSheet(i);
  },
  isetsheet: function (i, cpl) {
    this.index = i;
    this.cpl = cpl;
    this.sheetObj = this.cpl.getGcSheet(i);
  },
  currentRow: function () {

  },
  currentCol: function () {

  },
  setFixedCol: function (v) {
    this.sheetObj.setFrozenColumnCount(v - 1);
  },
  setFixedRow: function (v) {
    this.sheetObj.setFrozenRowCount(v - 1);
  },
  rowHeaderVisible: function (v) {
    if (v == null) {
      return this.sheetObj.getRowHeaderVisible();
    } else {
      return this.sheetObj.setRowHeaderVisible(v);
    }
  },
  colHeaderVisible: function (v) {
    if (v == null) {
      return this.sheetObj.getColumnHeaderVisible();
    } else {
      return this.sheetObj.setColumnHeaderVisible(v);
    }
  },
  insertRow: function (start, count) {
    this.sheetObj.addRows(start - 1, count);
  },
  insertCol: function (start, count) {
    this.sheetObj.addColumns(start - 1, count);
  },
  deleteRow: function (start, count) {
    this.sheetObj.deleteRows(start - 1, count);
  },
  deleteCol: function (start, count) {
    this.sheetObj.deleteColumns(start - 1, count);
  },
  customVar: function (vname) {
    if (vname == null) {
      var cname = this.sheetObj.getCustomName("RN:S:Name");
      if (cname != null && cname != "") {
        return cname.getExpression().name;
      }
      return "";
    }
    else {
      this.sheetObj.addCustomName("RN:S:Name", "=" + vname, 0, 0);
    }
  },
  getPrefixVarObjJs: function (varPrefix) {
    var retObj = {};
    var rg = this.cpl.getRangeByCustomVar(varPrefix + "*", this.index);
    rg.foreachJs(function (itemRg, index) {
      var cvar = itemRg.customVar();
      cvar = cvar.substring(varPrefix.length);
      retObj[cvar] = itemRg.text();
    });
    return retObj;
  },
  bind: function (obj, func) {
    this.sheetObj.bind(obj, func);
  },
  merge: function (r1, c1, r2, c2) {
    this.sheetObj.addSpan(r1 - 1, c1 - 1, r2 - r1 + 1, c2 - c1 + 1);
  },
  unMerge: function (r1, c1) {
    this.sheetObj.removeSpan(r1 - 1, c1 - 1);
  },
  sheetName: function (name) {
    if (name == null) {
      return this.sheetObj.getName();
    }
    this.sheetObj.setName(name);
    return name;
  },
  getIndex: function () {
    return this.index;
  }
}

//end Sheet

//generalCell  class
function cpGeneralCell(i) {
  this.a = i;
  this.flag = new Array('A', 'B'); //instance has two different flag
}

cpGeneralCell.prototype = {
  func: function () {
    return 33;
  }
}
//end generalCell class

//buttonCell class
function cpButtonCell(j) {
  cpGeneralCell.call(this, 1);
  this.j = j;
}

cpButtonCell.prototype = {
  func_sub: function () {
    return ++this.j;
  },

  func_sub2: function () {
    return ++this.j + 10;
  }
}

var cpUtil = {
  equalRg: function (srcRg, dstRg) {
    return srcRg.r1() == dstRg.r1() && srcRg.c1() == dstRg.c1() &&
      srcRg.r2() == dstRg.r2() && srcRg.c2() == dstRg.c2() && srcRg.s() == dstRg.s();
  },
  isRgInRg: function (container, chkedRg) {
    return chkedRg.r1() >= container.r1() && chkedRg.r2() <= container.r2()
      && chkedRg.c1() >= container.c1() && chkedRg.c2() <= container.c2();
  },
  gcRgToIcp: function (expr, sheet) {
    var icp = new icprange();
    icp.sheet = sheet;
    if (expr instanceof GcSpread.Sheets.Calc.Expressions.CellExpression || expr instanceof GcSpread.Sheets.Calc.Expressions.ExternalCellExpression) {
      var r1 = expr.row + 1;
      var c1 = expr.column + 1;
      icp.setRg(r1, c1, r1, c1, sheet, cpUtil.getAbsVal(!expr.rowRelative, !expr.columnRelative));
    }
    else if (expr instanceof GcSpread.Sheets.Calc.Expressions.RangeExpression || expr instanceof GcSpread.Sheets.Calc.Expressions.ExternalRangeExpression) {
      icp.setRg(expr.startRow + 1, expr.startColumn + 1, expr.endRow + 1, expr.endColumn + 1, sheet, cpUtil.getAbsVal(!expr.startRowRelative,
        !expr.startColumnRelative, !expr.endRowRelative, !expr.endColumnRelative));
    }
    else
      icp = null;
    return icp;
  },
  gcExprRgToIcp: function (expr) {
    var icp = cm.RefStrToRange(expr, true);
    return icp;
  },
  icpToRefStr: function (icp) {
    var str = cm.RgColRowToRefStr(icp.r1, icp.c1, icp.r2, icp.c2, icp.absR(), icp.absC(), icp.absR2(), icp.absC2());
    return str;
  },
  getAbsVal: function (br, bc, br2, bc2) {
    var val = bc ? 1 : 0;
    val += br ? 2 : 0;
    val += br2 ? 8 : 0;
    val += bc2 ? 4 : 0;
  },
  icpToGcCells: function (cpl, icp) {
    var gcsheet = cpl.getGcSheet(icp.sheet);
    return gcsheet.getCells(icp.r1 - 1, icp.c1 - 1, icp.r2 - 1, icp.c2 - 1);
  },
  icpToGcRange: function (icp) {
    var start = new GcSpread.Sheets.Range(icp.r1 - 1, icp.c1 - 1, icp.r2 - icp.r1 + 1, icp.c2 - icp.c1 + 1);
    return start;
  },
  rgToGcCells: function (cpl, sheet, r1, c1, r2, c2) {
    return cpl.getGcSheet(sheet).getCells(r1 - 1, c1 - 1, r2 - 1, c2 - 1);
  },
  colRowToGc: function (row, col) {
    row -= 1;
    col -= 1;
  },
  getOffsetToArr: function (theArrIcp, orgIcp) {
    var arrRet = [];
    for (var i = 0; i < theArrIcp.length; i++) {
      arrRet.push(this.getOffsetTo(orgIcp, theArrIcp[i]));
    }
    return arrRet;
  },
  getOffsetTo: function (orgIcp, theIcp) {
    var offIcp = new icprange();
    offIcp.varName = theIcp.varName;
    offIcp.c1 = orgIcp.c1 - theIcp.c1;
    offIcp.r1 = orgIcp.r1 - theIcp.r1;
    offIcp.r2 = orgIcp.r2 - theIcp.r2;
    offIcp.c2 = orgIcp.c2 - theIcp.c2;
    return offIcp;
  },
  getNewRange: function (cpl) {
    var cprg = new cpRange();
    cprg.isetcpl(cpl);
    return cprg;
  },
  getNewButtonCell: function () {
    var cellType = new GcSpread.Sheets.ButtonCellType();
    cellType.buttonBackColor("#FFFF00");
    cellType.text("button");
    return cellType;
  },
  getNewCheckBox: function () {
    var cellType1 = new GcSpread.Sheets.CheckBoxCellType();
    cellType1.textTrue("true");
    cellType1.textFalse("false");
    cellType1.textAlign(GcSpread.Sheets.CheckBoxTextAlign.right);
    cellType1.isThreeState(false);
    return cellType1;
  },
  getNewComboBox: function () {
    var cellType2 = new GcSpread.Sheets.ComboBoxCellType();
    cellType2.items(["item1", "item2", "item3"]);
    return cellType2;
  },
  getNewTextCell: function () {
    var cellType2 = new GcSpread.Sheets.TextCellType();
    return cellType2;
  },
  isButtonCell: function (obj) {
    return obj != null && obj instanceof GcSpread.Sheets.ButtonCellType;
  },
  isComboBoxCell: function (obj) {
    return obj != null && obj instanceof GcSpread.Sheets.ComboBoxCellType;
  },
  isCheckBoxCell: function (obj) {
    return obj != null && obj instanceof GcSpread.Sheets.CheckBoxCellType;
  },
  isTextCell: function (obj) {
    return obj != null && obj instanceof GcSpread.Sheets.TextCellType;
  },
  getAllFuncTree: function (funcGroup) {
    //0 -- 常用 1 -- 统计 2 -- 表 3 --- 其它
    var all = [];
    var common = {id: 0, text: '常用'};
    var tongji = {id: 1, text: '统计'};
    var celltable = {id: 2, text: '表'};
    var other = {id: 3, text: '其他'};
    all.push(common);
    all.push(tongji);
    all.push(celltable);
    all.push(other);

    common.children = [];
    common.children.push({
      functype: 0,
      paranum: 1,
      name: 'abs',
      rttype: 1,
      paratype: [],
      help: '获取绝对值数据'
    });
  },
  getAutoFillToGc: function (v) {
    switch (v) {
      case 0:
        return GcSpread.Sheets.AutoFillType.Auto;
      case 1:
        return GcSpread.Sheets.AutoFillType.CopyCells;
      case 2:
        return GcSpread.Sheets.AutoFillType.FillWithoutFormatting;
      case 3:
        return GcSpread.Sheets.AutoFillType.FillFormattingOnly;
    }
  },
  getAutoFillToCell: function (v) {

    if (v == GcSpread.Sheets.AutoFillType.Auto) {
      return 0;
    }
    else if (v == GcSpread.Sheets.AutoFillType.CopyCells) {
      return 1;
    }
    else if (v == GcSpread.Sheets.AutoFillType.FillWithoutFormatting) {
      return 2;
    }
    else if (v == GcSpread.Sheets.AutoFillType.FillFormattingOnly) {
      return 3;
    }
  }
}
//end buttonCell class


/////////////////////

var cellDgn = {
  onSelChange: function (obj, info) {
    cellDgnEvent && cellDgnEvent.onSelChange(obj, info);
  },
  onChange: function (obj, info) {
    cellDgnEvent && cellDgnEvent.onChange(obj, info);
  },
  onCellDoubleClick: function (obj, info) {
    cellDgnEvent && cellDgnEvent.onCellDoubleClick(obj, info);
  },
  onLeaveCell: function (obj, info) {
    cellDgnEvent && cellDgnEvent.onLeaveCell(obj, info);
  }
};
var cn = {
  isCellCusType:function(cell,typeEx){
    if (typeEx =="autocode"){
      return cell.tag().indexOf("cus:cd">=0);
    }
    else if (typeEx=="basedata"){
      return cell.tag().indexOf("cus:bsd">=0);
    }
    return false;
  },
  cprgToSqlFieldArr: function (cprg) {
    var farr = [];
    var sqlField = {};
    sqlField.fieldName = "sheetName";
    sqlField.fieldNameEx=sqlField.fieldName;
    sqlField.fieldType = 3;
    sqlField.fieldLength = 255;
    sqlField.cellPos = cprg.getCurSheet().sheetName();
    farr.push(sqlField);
    var fieldIndex = 0;
    cprg.foreachCell(function (cpl, itemRg, index) {
      var sqlField = {};
      sqlField.fieldName = "F" + fieldIndex++;
      sqlField.fieldNameEx=sqlField.fieldName;
      sqlField.fieldTypeEx = cn.cellTypeToFieldTypeEx(itemRg.cellType(),itemRg.formatter(), itemRg.tag());
      sqlField.fieldType = cn.cellTypeToFieldType(itemRg.cellType(),itemRg.formatter(), itemRg.tag());
      sqlField.fieldLength = 255;
      sqlField.cellPos = itemRg.toRgStr();
      farr.push(sqlField);
    });
    return farr;
  },
  cprgToFieldVar2: function (cpl) {//将rg定义名称
    for (var i = 0; i < cpl.formObj.tableArr.length; i++) {
      var tableItem = cpl.formObj.tableArr[i];
      var cpsht = cpl.getSheetByVar(tableItem.sheetName);
      for (var t = 0; t < tableItem.columns.length; t++) {
        var cols = tableItem.columns[t];
        if (cols.fieldName == 'sheetName') {
        }
        else {
          var ret = cm.RefStrToRange(cols.cellPos, true, cpsht.getIndex());
          var cpRg = cpl.getRange(ret.r1, ret.c1, ret.r2, ret.c2, ret.sheet);
          cpRg.customVar("RD:" + tableItem.oid + ":" + cols.fieldName);
        }
      }
      if (tableItem.tableType == 2) {//子表数据项
        var htRg = cpl.getRangeByCustomVar("RD:" + tableItem.oid + ":*");
        htRg.mergeToOne().customVar("RD:HTRG:" + tableItem.oid);
      }
    }
  },
  setAutoCodeRg:function(cpl, gen){
    var rgArr = [];
    for (var i = 0; i < cpl.formObj.tableArr.length; i++) {
      var tableItem = cpl.formObj.tableArr[i];
      var cpsht = cpl.getSheetByVar(tableItem.sheetName);
      for (var t = 0; t < tableItem.columns.length; t++) {
        var cols = tableItem.columns[t];
        if (cols && cols.fieldTypeEx=="autocode"){
          var cpRg = cpl.getRangeByCustomVar("RD:" + tableItem.oid + ":" + cols.fieldName, cpsht.getIndex());
          rgArr.push(cpRg);
        }
      }
    }

    for ( var i=0;i<rgArr.length; i++ ){
      var code = rgArr[i].tag();
      code=cm.strSplitIdx(code,":",1);
      if(code){
        var ret = yddser.getCode(code);
        if (cm.dataNotOk(ret)){
          return false;
        }
        if ( ret.data.codeGen ==gen ){
          ret = yddser.getNextCode(ret.data.oid);
          if (cm.dataNotOk(ret)){
            return false;
          }
          rgArr[i].text(ret.data);
        }
      }
    }
  },
  getReqMDData: function (cpl, packId, formId, parentId, sheetName, tablearr, asNew) {
    var reqdata = new ReqResTableData();
    reqdata.dataStatus = 1;//addData
    for (var i = 0; i < tablearr.length; i++) {
      var item = tablearr[i];
      var tableData = new TableData();
      tableData.packId = packId;
      tableData.formId = formId;
      tableData.tableId = item.oid;
      tableData.dataIndex = "";

      var idx = this.getSheetIndex(cpl, item.sheetName);
      if (idx == -1) {
        return null;
      }
      var sht = cpl.getSheet(idx);
      var rg = cpl.getRangeByCustomVar("RD:" + item.oid + ":*", idx);
      var rgdid = cpl.getRangeByCustomVar("RDI:" + item.oid + ":diid*", idx);
      var columns = {};

      if (item.tableType == 1) {
        //主表数据项
        if (rgdid.areaCount() == 1) {
          var vv = rgdid.customVar();
          if ( asNew == 1 ){
            columns["oid"]="";
            tableData.dataIndex ="";
          }
          else {
            columns["oid"] = cm.strSplitIdx(vv, ":", 3);
            tableData.dataIndex = cm.strSplitIdx(vv, ":", 2);
          }
          reqdata.dataStatus = 2;//modify data
        }
        rg.foreachJs(function (irg, index) {
          var itemdata = new Array();
          var dataSht = {};
          columns["sheetName"] = sheetName;
          var vnames = irg.customVar();
          vnames = cm.strSplit(vnames, ":");
          var data = {};
          columns[vnames[2]] = irg.text();
        });
        tableData.columns = [];
        tableData.columns.push(columns);
      }
      else if (item.tableType == 2) {
        //子表数据项
        var htRg = cpl.getRangeByCustomVar("RD:HTRG:" + item.oid, idx);
        if (htRg == null) {
          $('#my-alert .am-modal-bd').text("未发现子表数据项");
          $('#my-alert').modal();
          return;
        }
        if (rgdid.areaCount() == 1) {
          var vv = rgdid.customVar();
          if ( asNew==1){
            tableData.dataIndex = "";
          }
          else {
            tableData.dataIndex = cm.strSplitIdx(vv, ":", 2);
          }
          reqdata.dataStatus = 2;//modify data
          if (cpl.tmpData != null && cpl.tmpData.deletedDids != null) {
            tableData.deletedDids = cpl.tmpData.deletedDids[item.oid];
          }
        }
        var vals = htRg.htRgGetAllVal(null, function (outObj, j, jname, offRg, idx) {
          if (j == 0) {
            outObj.sheetName = sheetName;
            if (asNew == 1){
              outObj.oid="";
            }
            else {
              outObj.oid = offRg.tag();
            }
          }
        });
        tableData.columns = vals;
      }
      reqdata.tableArr.push(tableData);
    }
    return reqdata;
  },
  getCplFormObj: function (cpl) {
    return cpl.formObj;
  },
  setCplFormTableArrPos: function (cpl, funSheet, funRg) {
    if (cpl.formObj.datasetState == 0) {
      return;
    }
    for (var i = 0; i < cpl.formObj.tableArr.length; i++) {
      var tableItem = cpl.formObj.tableArr[i];
      var cpsht = cpl.getSheetByVar(tableItem.sheetName);
      funSheet&&funSheet(cpsht);
      for (var t = 0; t < tableItem.columns.length; t++) {
        var cols = tableItem.columns[t];
        if (cols.fieldName == 'sheetName') {
          if (cpsht != null) {
            cols.cellPos = cpsht.sheetName();
          }
        } else {
          var cpRg = cpl.getRangeByCustomVar("RD:" + tableItem.oid + ":" + cols.fieldName, cpsht.getIndex());
          funRg&&funRg(cpRg);
          cols.cellPos = cpRg.toRgStr();
        }
      }
    }
  },
  setCplFormTableArrPosNone: function (cpl, funSheet, funRg) {
    if (cpl.formObj.datasetState == 0) {
      return;
    }
    for (var i = 0; i < cpl.formObj.tableArr.length; i++) {
      var tableItem = cpl.formObj.tableArr[i];
      var cpsht = cpl.getSheetByVar(tableItem.sheetName);
      funSheet&&funSheet(cpsht);
      for (var t = 0; t < tableItem.columns.length; t++) {
        var cols = tableItem.columns[t];
        if (cols.fieldName == 'sheetName') {
        } else {
          var cpRg = cpl.deleteCustomVar("RD:" + tableItem.oid + ":" + cols.fieldName, cpsht.getIndex());
          funRg&&funRg(cpRg);
        }
      }
    }
    cpl.formObj.tableArr=[];
  },
  setCplFormData: function (cpl, reqresdata) {
    for (var i = 0; i < reqresdata.tableArr.length; i++) {
      var tabledata = reqresdata.tableArr[i];
      var tableId = tabledata.oid;
      var sheetIndex = cn.getSheetIndex(cpl, tabledata.sheetName);
      if (tabledata.tableType == 1) {
        var dataitem = tabledata.dataList[0];
        var cprgdid = cpl.getRangeByCustomVar("RDI:" + tableId + ":" + dataitem["dataIndex"] + ":" + dataitem["oid"], sheetIndex);
        if (cprgdid != null && cprgdid.areaCount() > 0) {
          cprgdid.deleteCustomVar(false);
        }
        var cprg = cpl.getRangeByCustomVar("RD:" + tableId + ":F*", sheetIndex);
        cprg.getLTRg().getArea(0).customVar("RDI:" + tableId + ":" + dataitem["dataIndex"] + ":" + dataitem["oid"]);
        cprgdid = cpl.getRangeByCustomVar("RDI:" + tableId + ":diid*", sheetIndex);
        cprg.foreachJs(function (rg, areaIndex) {
          var fld = cn.getRgNameFld(rg.customVar());
          rg.value(dataitem[fld]);
        });
      }
      else if (tabledata.tableType == 2) {
        if (tabledata.dataList.length <= 0) {
          continue;
        }

        var diidName = "RDI:" + tableId + ":" + tabledata.dataList[0]["dataIndex"] + ":subTable";
        var cprgdid = cpl.getRangeByCustomVar(diidName, sheetIndex);
        if (cprgdid != null && cprgdid.areaCount() > 0) {
          cprgdid.deleteCustomVar(false);
        }
        var htRgName = "RD:HTRG:" + tabledata.oid;
        var htRg = cpl.getRangeByCustomVar(htRgName, sheetIndex);
        var headRg = htRg.htRgGetHead();
        headRg.getLTRg().customVar(diidName);
        htRg.htRgFillVal(tabledata.dataList, function (offRg, idx, colName, rowData) {
          if (idx == 0) {
            offRg.tag(rowData.oid);
          }
        });
      }
    }
  },
  initCpl: function (cpl) {
    var max = this.getSheetNameMaxIndex(cpl);
    cpl.foreachSheetJs(function (sht, idx) {
      if (sht.customVar() == "") {
        sht.customVar("RefShtS" + max++);
      }
    });
  },
  addSheet: function (cpl, index, sheetName) {
    var max = this.getSheetNameMaxIndex(cpl);
    cpl.addSheet(index, sheetName);
    cpl.getSheet(index).customVar("RefShtS" + max);
  },
  getSheetNameMaxIndex: function (cpl) {
    var max = 0;
    var sht = new cpSheet();
    cpl.foreachSheetJs(function (sht, idx) {
      vname = sht.customVar();
      if (vname != null) {
        vname = vname.substring("RefShtS".length);
        if (cm.strToInt(vname) >= max) {
          max = cm.strToInt(vname) + 1;
        }
      }
    });
    return max;
  },
  getSheetIndex: function (cpl, name) {
    for (var i = 0; i < cpl.getSheetCount(); i++) {
      if (cpl.getSheet(i).customVar() == name) {
        return i;
      }
    }
    return -1;
  },
  getRgNameFld: function (name) {
    return cm.strSplit(name, ":")[2];
  },
  cellTypeToFieldType:function(ctype,formatter,tag){
    if (ctype == null ){
      if (formatter==null){
        return 3;
      }
      else if (formatter.indexOf(".")>=0){
        return 2;
      }
      return 3;
    }
    else if(ctype instanceof GcSpread.Sheets.CheckBoxCellType ){
      return 1;
    }
    else if ( ctype instanceof GcSpread.Sheets.ComboBoxCellType ){
      return 3;
    }
    else if ( ctype instanceof GcSpread.Sheets.BaseCellType){
      var vv = formatter;
      return 3;
    }
    else if ( ctype instanceof GcSpread.Sheets.TextCellType){
      var vv = formatter;
      return 4;
    }
    return 3;
  },
  cellTypeEx:function (rg) {
    return cn.cellTypeToFieldTypeEx(rg.cellType(),rg.formatter(), rg.tag());
  },
  cellTypeToFieldTypeEx:function (ctype,formatter,tag) {
    if ( tag != null ){
      if (tag.indexOf("cus:cd")>=0){
        return "autocode";
      }
      else if(tag.indexOf("cus:bsd")>=0){
        return "basedata";
      }
    }
    return "";
  },
  fieldTypeExToFieldType:function (fieldEx) {
    if (fieldEx == "text") {
      return 3;
    }
    else if (fieldEx == "num") {
      return 2;
    }
    else if (fieldEx == "checkbox") {
      return 2;
    }
    else if (fieldEx == "combobox") {
      return 2;
    }
    else if (fieldEx == "datetime"){
      return 1;
    }
    else if (fieldEx=="autocode"){
      return 3;
    }
  },
  setTreeItem: function (ret, child, setId, setName, nodeParentType, nodeChildType) {
    if (ret != null) {
      cm.setTreeEachItem(ret.data, child, function (obj) {
        obj.id = obj[oid];
        obj.text = obj[setName];
        if (obj[child] != null) {
          obj.type = nodeParentType;
        }
        else {
          obj.type = nodeChildType;
        }
      });
    }
  },
  showOpenFile:function (callBack) {
    g_openFile.$data.callBack = callBack;
    $('#my-localFile').modal({});
  },
  showFailedDlg: function (msg) {
    cm.myAlert(msg);
  },
  showFailedDlg2: function (msg, inData, func) {
    cm.myAlertFunc(msg,inData,func);
  },
  getRetData: function (data, showMsg) {
    showMsg = true;
    var retData = null;
    if (data == null) {
      data = {code:-1, msg:"调用服务失败null"};
      toastr.clear();
      toastr.error(data.msg);

    }
    else if (cm.dataOk(data) && showMsg) {
      toastr.clear();
      toastr.success(data.msg);
    } else if (cm.dataNotOk(data)) {
      toastr.clear();
      toastr.error(data.msg);
    }
    return data;
  },
  getRetCode: function (data, showMsg) {
    showMsg = true;
    if (cm.dataOk(data) && showMsg) {
      toastr.clear();
      toastr.success(data.msg);
    } else if (cm.dataNotOk(data)) {
      toastr.clear();
      toastr.error(data.msg);
    }
    return data.code;
  },
  getRetMsg: function (data) {
    if (data == null) {
      return '调用服务器失败,请重试';
    }
    else {
      return data.msg;
    }
  },
  yddToJstree: function (obj) {
    obj['id'] = obj.oid;
    obj['text'] = obj.name;
    if (cm.strStartWith(obj.oid, 'fm')) {
      obj.type = 'file';
    }
    else if (cm.strStartWith(obj.oid, 'pk')) {
      obj.type = 'root';
    }
    else if (cm.strStartWith(obj.oid, 'dp')) {
      obj.type = 'department';
    }
    else if (cm.strStartWith(obj.oid, 'rt')) {
      obj.type = 'department';
    }
  },
  openDeptUser: function (e, data) {
    if (data.node.original != null) {
      var users = yddser.getDeptUser(data.node.original.oid);
      return users;
    }
  },
  openForm: function (e, data, original) {
    var orgi = original;
    if (orgi == null ){
      orgi = data.node.original;
    }
    if (orgi == null || !cm.strStartWith(orgi.oid, "fm"))
      return;

    var form = cn.getCurTabForm();
    if (form != null && form.oid == orgi.oid)
      return;
    var tabFnd = cn.getTabId(orgi.oid);
    if (tabFnd != null) {
      cn.setCurrentTabGc($('.chrome-tabs-shell'), tabFnd);
      return
    }

    var formData = yddser.getForm(orgi.oid);//form和tableArr data
    if ( cm.dataNotOk(formData) ){
      cm.myAlert("打开表单失败!");
      return;
    }
    formData = formData.data;
    var tabD = cn.genTabData("", formData.name, orgi);
    var cp = cn.addTab(tabD);
    cp.loadFromJsonStr(formData.styleData);
    cp.formObj = formData;
    return cp;
  },
  resetForm: function (cpl) {
    if ( cpl == null ){
      cpl = cn.getCurTabForm().cellPlus;
    }
    cpl.loadFromJsonStr(cpl.formObj.styleData);
  },
  addFormDiv: function (e, data) {
    var divId = 'gcDiv-' + data.id;
    $("#markLink").append('<div class="gcDiv" id="' + divId + '">' + '</div>');
    return new cellPlus($("#" + divId)[0]);
  },

  //
  deleteFormDiv: function (data) {
    var divId = 'gcDiv-' + data.id;
    $("#" + divId).remove();
  },

  hideFormDiv: function (data, hide) {
    var divId = 'gcDiv-' + data.id;
    if (hide)
      $("#" + divId).css("display", "none");
    else
      $("#" + divId).css("display", "block");
  },

  tabClick: function (shell, tab) {
    var $currentTabB = shell.find('.chrome-tab-current');
    var ret = chromeTabs.setCurrentTab(shell, tab);
    var $currentTab = shell.find('.chrome-tab-current');

    if ($currentTabB.data('tabData').data == $currentTab.data('tabData').data)
      return;
    else {
      cn.hideFormDiv($currentTabB.data('tabData').data, true);
      cn.hideFormDiv($currentTab.data('tabData').data, false);
    }

    return ret;
  },
  setCurrentTabGc: function (shell, tab) {
    var $currentTabB = shell.find('.chrome-tab-current');
    var ret = chromeTabs.setCurrentTab(shell, tab);
    var $currentTab = shell.find('.chrome-tab-current');

    if ($currentTabB.data('tabData').data == $currentTab.data('tabData').data)
      return;
    else {
      cn.hideFormDiv($currentTabB.data('tabData').data, true);
      cn.hideFormDiv($currentTab.data('tabData').data, false);
    }

    return ret;
  },
  tabClose: function (shell, tab) {

    var tabD = tab.data('tabData').data;
    cn.deleteFormDiv(tabD);
    chromeTabs.closeTab(shell, tab);

    $currentTab = $('.chrome-tabs-shell').find('.chrome-tab-current');
    if ($currentTab.data('tabData') == null) {
    }
    else {
      cn.hideFormDiv($currentTab.data('tabData').data, false);
    }

  },
  genTabData: function (icon, tabTitle, dataobj) {
    return {
      favicon: icon,
      title: tabTitle,
      data: dataobj
    }
  },
  getDataColName: function (data) {

  },
  getCurTabForm: function () {
    var tab = $('.chrome-tabs-shell').find('.chrome-tab-current');
    if (tab.data('tabData') == null) {
      return null;
    }
    return tab.data('tabData').data;
  },
  getCurCellPlus: function () {
    var tabCur = cn.getCurTabForm();
    if (tabCur == null)
      return null;
    return tabCur.cellPlus;
  },
  addTab: function (data) {
    var $currentTabB = $('.chrome-tabs-shell').find('.chrome-tab-current');
    if ($currentTabB.data('tabData') == null) {

    }
    else {
      cn.hideFormDiv($currentTabB.data('tabData').data, true);
    }

    var newTab = chromeTabs.addNewTab($('.chrome-tabs-shell'), data);
    var cellP = cn.addFormDiv(null, data.data);
    cellP.bind(GcSpread.Sheets.Events.CellChanged, function (e, info) {
      if (info.sheetArea === GcSpread.Sheets.SheetArea.viewport) {
        cellDgn.onChange(e, info);
      }
    });

    cellP.bind(GcSpread.Sheets.Events.SelectionChanged, function (e, info) {
      cellDgn.onSelChange(e, info);
    });

    cellP.bind(GcSpread.Sheets.Events.LeaveCell, function (sender, args) {
      cellDgn.onLeaveCell(sender, args);
    });

    cellP.bind(GcSpread.Sheets.Events.CellDoubleClick, function (sender, args) {
      cellDgn.onCellDoubleClick(sender, args);
    });

    newTab.data('tabData').data.cellPlus = cellP;
    return cellP;
  },
  getTabId: function (tabId) {
    var find = false;
    var $tab, $tabFnd;
    $('.chrome-tabs-shell').find('.chrome-tab').each(function () {
      $tab = $(this);
      console.log($tab.data('tabData').data);
      if (find == false && $tab.data('tabData').data.id == tabId) {
        $tabFnd = $tab;
        find = true;
      }

    });
    //chromeTabs.setCurrentTab($('.chrome-tabs-shell'), $tab);
    return $tabFnd;
  },
  getTabCell: function (formId) {
    var find = false;
    var $tab, $tabFnd;
    $('.chrome-tabs-shell').find('.chrome-tab').each(function () {
      $tab = $(this);
      console.log($tab.data('tabData').data);
      if (find == false && $tab.data('tabData').data.id == formId) {
        $tabFnd = $tab;
        find = true;
      }

    });
    //chromeTabs.setCurrentTab($('.chrome-tabs-shell'), $tab);
    return $tabFnd.data('tabData').data;
  },
  getDataKeyCols: function (obj) {
    var keyCol = [];
    cm.forEachKeys(obj, function (obj,k) {

      if (k == "tableId" || k == "dataIndex" || k == "oid" || k == "sheetName" || k == "userId" || k == "updateTime") {

      }
      else {
        var item = {};
        item.name = k;
        item.label = k;
        keyCol.push(item);
      }

    });
    return keyCol;
  }

};


//jquery custom contro for gc

function DatePickerCellType() {
}
if ( ns != null ){
  DatePickerCellType.prototype = new ns.CustomCellType();

  DatePickerCellType.prototype.createEditorElement = function (context) {
    //Create input presenter.
    return document.createElement("input");
  };
  DatePickerCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
    //Initialize input editor.
    if (editorContext) {
      $editor = $(editorContext);
      ns.CustomCellType.prototype.activateEditor.apply(this, arguments);
      $editor.datepicker();
      $editor.css("position", "absolute");
      $editor.attr("gcUIElement", "gcEditingInput");
      $(".ui-datepicker").attr("gcUIElement", "gcEditingInput");
    }
  }
  DatePickerCellType.prototype.deactivateEditor = function (editorContext, context) {
    //Remove input editor when end editor status.
    if (editorContext) {
      var element = editorContext;
      $(element).datepicker("hide");
      $(element).datepicker("destroy");
    }
    ns.CustomCellType.prototype.deactivateEditor.apply(this, arguments)
  };
  DatePickerCellType.prototype.setEditorValue = function (editor, value, context) {
    //Sync value from Cell value to editor value.
    $(editor).datepicker("setDate", value);
  };
  DatePickerCellType.prototype.getEditorValue = function (editor, context) {
    //Sync value from editor value to cell value.
    return $(editor).datepicker("getDate");
  };
  DatePickerCellType.prototype.updateEditor = function (editorContext, cellStyle, cellRect, context) {
    if (editorContext) {
      $editor = $(editorContext);
      $editor.css("width", cellRect.width - 1);
      $editor.css("height", cellRect.height - 3);
    }
  };
}


(function($) {
  var privateFunction = function() {
    // 代码在这里运行
  }

  var methods = {
    init: function(options) {
      return this.each(function() {
        var $this = $(this);
        var settings = $this.data('departmentpicker');

        if(typeof(settings) == 'undefined') {

          var defaults = {
            propertyName: 'value',
            entry: [{name: '请选择', value: ''}],
            isShowing: false,
            onSelect: function() {
              $this.val(this.value);
              $('#ui-departmentpicker-div').hide();
              $(document).unbind('mousedown.departmentpicker');
            },
            onSomeEvent: function() {}
          }

          settings = $.extend({}, defaults, options);

          $this.data('departmentpicker', settings);
        } else {
          settings = $.extend({}, settings, options);
        }

        // 代码在这里运行
        if($('#ui-departmentpicker-div').length == 0) {
          var dpt = document.createElement('div');
          $(dpt).attr('id', 'ui-departmentpicker-div');
          $(dpt).addClass('ui-departmentpicker');
          $(dpt).append('<select></select>');
          $(dpt).appendTo('body');
        }


        $this.bind('focus', function() {
          settings.isShowing = true;
          $select = $('#ui-departmentpicker-div select');
          $select.empty();
          for(var i = 0; i < settings.entry.length; i++) {
            $select.append('<option value="' + settings.entry[i].value + '">' + settings.entry[i].name + '</option>');
          }
          var top = $this.offset().top + $this.outerHeight();
          var left = $this.offset().left;
          $('#ui-departmentpicker-div').css({'position': 'absolute', 'top': top + 'px', 'left': left + 'px'}).show();
          if($this.val() != null && $this.val() != '') {
            $select.val($this.val());
          }
          $select.unbind('change');
          $select.bind('change', settings.onSelect);
          $(document).bind('mousedown.departmentpicker', function() {
            var el = event.target;
            var cal = $('#ui-departmentpicker-div')[0];

            while (true) {
              if (el == cal || el == $this.get(0)) {
                break;
              } else if (el == document) {
                settings.isShowing = false;
                $('#ui-departmentpicker-div').hide();
                $(document).unbind('mousedown.departmentpicker');
                break;
              } else {
                el = $(el).parent()[0];
              }
            }
          })
        })

      });
    },
    hide: function(options) {
      return $(this).each(function() {
        var $this = $(this);

        var settings = $this.data('departmentpicker');
        if(settings.isShowing) {
          $('#ui-departmentpicker-div').hide();
          $(document).unbind('mousedown.departmentpicker');
        }
      })
    },
    destroy: function(options) {
      return $(this).each(function() {
        var $this = $(this);

        $this.removeData('departmentpicker');
      });
    },
    val: function(options) {
      var someValue = this.eq(0).html();

      return someValue;
    },
    getDepartment: function(options) {
      return $(this).val();
    },
    setDepartment: function(options) {
      return $(this).each(function() {
        var $this = $(this);

        $this.val(options);
      });
    }
  };

  $.fn.departmentpicker = function() {
    var method = arguments[0];

    if(methods[method]) {
      method = methods[method];
      arguments = Array.prototype.slice.call(arguments, 1);
    } else if( typeof(method) == 'object' || !method ) {
      method = methods.init;
    } else {
      $.error( 'Method ' +  method + ' does not exist on jQuery.departmentpicker' );
      return this;
    }

    return method.apply(this, arguments);

  }

})(jQuery);

function DepartmentPickerCellType() {
}
if ( ns != null ){
  DepartmentPickerCellType.prototype = new ns.CustomCellType();

  DepartmentPickerCellType.prototype.createEditorElement = function (context) {
    //Create input presenter.
    return document.createElement("input");
  };
  DepartmentPickerCellType.prototype.activateEditor = function (editorContext, cellStyle, cellRect, context) {
    //Initialize input editor.
    if (editorContext) {
      $editor = $(editorContext);
      ns.CustomCellType.prototype.activateEditor.apply(this, arguments);

      $editor.css("position", "absolute");
      $editor.departmentpicker({entry: [{name: 'Developer', value: 'Developer'}, {name: 'HR', value: 'HR'},
        {name: 'Marketing', value: 'Marketing'}, {name: 'Sales', value: 'Sales'}]});
      $editor.attr("gcUIElement", "gcEditingInput");
      $(".ui-departmentpicker").attr("gcUIElement", "gcEditingInput");
    }
  }
  DepartmentPickerCellType.prototype.deactivateEditor = function (editorContext, context) {
    //Remove input editor when end editor status.
    if (editorContext) {
      var element = editorContext;
      $(element).departmentpicker("hide");
      $(element).departmentpicker("destroy");
    }
    ns.CustomCellType.prototype.deactivateEditor.apply(this, arguments)
  };
  DepartmentPickerCellType.prototype.setEditorValue = function (editor, value, context) {
    //Sync value from Cell value to editor value.
    $(editor).departmentpicker("setDepartment", value);
  };
  DepartmentPickerCellType.prototype.getEditorValue = function (editor, context) {
    //Sync value from editor value to cell value.
    return $(editor).departmentpicker("getDepartment");
  };
  DepartmentPickerCellType.prototype.updateEditor = function (editorContext, cellStyle, cellRect, context) {
    if (editorContext) {
      $editor = $(editorContext);
      $editor.css("width", cellRect.width - 1);
      $editor.css("height", cellRect.height - 3);
    }
  };
}
